using System;
using System.Collections;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI;
using System.Drawing;
using Microsoft.SharePoint;
using net.windward.api.csharp;
using System.IO;
using System.Net;
using System.Data.Common;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxMenu;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxTabControl;
using Microsoft.SharePoint.WebControls;
using System.Data;
using net.windward.tags;
using net.windward.utils.ado;
using System.Xml;
using System.Web;
using System.Configuration;
using System.Web.Configuration;
using System.Reflection;
using System.Collections.Generic;
using System.Web.Caching;
using net.windward.util;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Globalization;
using net.windward.format;
using DevExpress.Web.ASPxScheduler.Controls;
using WC = System.Web.UI.WebControls;
using Microsoft.SharePoint.Administration;
using Kailua.net.windward.utils.datetime;
using DevExpress.Data;
using log4net;
using Kailua.net.windward.utils;
using WindwardArrow.net.windward.arrow.datasource.ado;
using WindwardArrow.net.windward.arrow.datasource.xml;
using WindwardArrow.net.windward.arrow.datasource;
using WindwardArrow.net.windward.arrow;
//using WindwardArrow.net.windward.arrow.schedule;
//using WindwardArrow.net.windward.arrow.schedule.run;
using WindwardArrow.net.windward.arrow.tools;
using ArrowScheduleCore;


namespace ArrowWebParts
{
    public partial class ConfigureReport : LayoutsPageBase
    {
        // Fields and Properties 
        /// <summary>
        /// <para>Finish message format string for insta run.</para>
        /// <para>"Report has been successfully generated to:&lt;br&gt;&lt;br&gt; &lt;b&gt;{0} -> {1}&lt;/b&gt;&lt;br&gt;&lt;br&gt;&lt;br&gt;"</para>
        /// </summary>
        private const string INSTA_FIN_MSG_FORMAT = "Report has been successfully generated to:<br><br> <b>{0} -> {1}</b><br><br><br>";

        private static int WizzyWidth = 850;
        private static int WizzyHeight_assemble = 620;
        private static int WizzyHeight_schedule = 559;
        private ASPxButton closeButton;
        string listId = "listId";
        string itemId = "itemId";
        string itemUrl = "itemUrl";
        string action = "none";
        private static readonly string VS_FOLDR_OUT_GUID = "folderOutGUID";
        private static readonly string VS_OUT_SITE_GUID = "OutputSiteGUID";
        private static readonly string VS_RPT_OUT_FOLDR_GUID = "ReportOutputFolderGUID";
        private static readonly string VS_TEMPL_SITE_GUID = "TemplateSiteGUID";
        private static readonly string VS_TEMPL_GUID = "TemplateGUID";

        private Label[] variableNameLabelArray_runreport; //also used by assemble webpart 
        private Label[] variableRequiredLabelArray_runreport;
        private Label[] variableTypeLabelArray_runreport;
        private TextBox[] variableValueTextBoxArray_runreport;//also used by assemble webpart
        private DropDownList[] variableValueDropDownListArray_runreport;

        //Shared stuff between configure and assemble
        private Label four;
        private SPFileSelector outputFolderSelector;
        private SPFileSelector rptOutLocFolderSelector;

        private static ILog log = LogManager.GetLogger(typeof(ConfigureReport));

        //Configure a Report Stuff
        #region RunAReport

        Table runReportTable;

        protected Label test;
        protected Label runReportHeader;
        protected Label one;
        protected Label two;
        protected Label three;
        protected Label reportNameLabel;
        protected ASPxTextBox reportName;
        private LiteralControl finalLiteral;
        private ASPxLabel errorMessage_runreport;
        private ASPxLabel errorMessageVars_runreport;
        private Label selDocLibLabel;
        static string imageDir = "1033/images/arrow/";

        ASPxButton generateButton;

        private const string RPT_DOCX = "DOCX";
        private const string RPT_SML = "SML";
        private const string RPT_PDF = "PDF";
        private const string RPT_PPTX = "PPTX";
        private const string RPT_RTF = "RTF";
        private const string RPT_WML = "WML";
        private const string RPT_XLS = "XLS";
        private const string RPT_XLSX = "XLSX";
        private const string RPT_HTML = "HTML";
        private DropDownList runReportOutputList;
        #endregion

        //Assemble a Report stuff
        #region AssembleReport
        private Wizard wizzy;
        private TextBox titleTextBox;
        private TextBox descriptionTextBox;
        private TextBox reportNameTextBox;
        private RequiredFieldValidator titleTextBoxValidator;
        private DropDownList templateSiteDropDownList;
        private DropDownList templateLibraryDropDownList;
        private DropDownList templateFileDropDownList;
        private RequiredFieldValidator templateFileDropDownListValidator;
        private DropDownList saveLocationSiteDropDownList;
        private DropDownList saveLocationLibraryDropDownList;
        private RequiredFieldValidator saveLocationLibDropDownListValidator;

        private Label[] dataSourceSpecLabelArray;
        private DropDownList[] dataSourceSpecSiteDropDownListArray;
        private DropDownList[] dataSourceSpecLibraryDropDownListArray;
        private DropDownList[] dataSourceSpecFolderDropDownListArray;
        private DropDownList[] dataSourceSpecFileDropDownListArray;

        //Variable stuff for assemble webpart
        private Label[] variableNameLabelArray; //also used by assemble webpart 
        private TextBox[] variableValueTextBoxArray;//also used by assemble webpart
        private DropDownList[] variableValueDropDownListArray;
        private CheckBox[] variableRequiredCheckBoxArray;
        private CheckBox[] variableHiddenCheckBoxArray;
        private Label[] variableTypeLabels;
        private TextBox[] variableDescriptionTextBoxArray;

        private TextBox[] variableDefaultValueTextBoxArray;

        // SELECT TYPE PARAMETER
        private TextBox[] variableDataNameTextBoxArray;
        private TextBox[] variableCountTextBoxArray;
        private TextBox[] variableAllTextBoxArray;
        private Label[] variableDataNameLiteralControlArray;
        private Label[] variableCountLabelLiteralControlArray;
        private Label[] variableAllLabelLiteralControlArray;
        private Label[] variableValueLabelLiteralControlArray;


        private Label titleSummaryLabel;
        private Label descriptionSummaryLabel;
        private Label locationSummaryLabel;
        private Label templateSummaryLabel;

        private Label finalStatusLabel;

        // assemble step 4 (review)
        Label assemblyName_val;
        Label description_val;
        Label templateFilename_val;
        Label saveLocation_val;
        Label reportOutputLocation_val;
        Label generatedReportName_val;

        private TabPage overviewTab;
        private ASPxPageControl tabs;

        //Step 1 Tab
        private ASPxTextBox titleTextbox;
        private ASPxMemo descriptionTextbox;
        private ASPxGridView docList2;
        private ASPxMenu menu;
        private ASPxMenu[] assembleDSLib;
        private SPDataSource dataSource;
        private Label five;
        private ASPxLabel errorMessageLabel;
        private ASPxLabel errorMessageLabel2;
        const int MAX_NUMBER_DATASOURCES = 20;

        string overviewImage = imageDir + "overviewStepAssemble.png";
        string variableImage = imageDir + "dataStep.png";
        string reviewImage = imageDir + "reviewStep_final.png";
        string assemblyImage = imageDir + "assembleStep.png";
        string datasourceImage = imageDir + "datasourceStep.png";
        private string scheduleImage = imageDir + "scheduleStep.png";

        #endregion

        //Schedule a Report Stuff
        #region ScheduleReport

        private Label[] variableNameLabelArray_schedule; //also used by assemble webpart 
        private Label[] variableRequiredLabelArray_schedule;
        private Label[] variableTypeLabelArray_schedule;
        private TextBox[] variableValueTextBoxArray_schedule;//also used by assemble webpart
        private DropDownList[] variableValueDropDownListArray_schedule;

        Label templateOv;
        Label dataOv;
        Label varOv;
        Label reviewOv;

        ASPxLabel lblSuccess;
        /// <summary>
        /// Displays status information contained in infoMessage;
        /// </summary>
        private Label lblStatus;

        /// <summary>
        /// for selecting the values of the parameters
        /// </summary>
        private ParameterValueSelector parmSelector;
        /// <summary>
        /// For setting the schedule
        /// </summary>
        private ScheduleSelector scheduleSelector;
        /// <summary>
        /// For selecting the output properties
        /// </summary>
        private IOutputSelector outputSelector;
        /// <summary>
        /// The main content of this web part, a wizard.
        /// </summary>
        private Wizard schedWizard;
        /// <summary>
        /// the wizard step index of parameter value selection
        /// </summary>
        private const int STEP_PARAMETER_SELECTION = 0;
        /// <summary>
        /// the wizard step index of schedule selection
        /// </summary>
        private const int STEP_SCHEDULE_SELECTION = 1;
        /// <summary>
        /// the output selection tab index
        /// </summary>
        private const int STEP_OUTPUT_SELECTION = 2;
        /// <summary>
        /// the review tab index
        /// </summary>
        private const int STEP_REVIEW = 3;

        private Control reviewControl;

        private HiddenField hidStartOver;

        private static readonly string ERROR_HEADER = "<p><b><span style=\"color: red\">ERROR:&nbsp;</span>";
        private static readonly string ERROR_TAIL = "</b></p>";

        /// <summary>
        /// Indicates if the product is licensed.  All methods return immediately if not.
        /// </summary>
        private bool isLicensed = false;

        // new ui fields
        private static Style headerStyle;
        private static Style normalStyle;
        private static Style normalBoldStyle;
        #endregion

        private const string filterIncludeScriptKey = "myFilterIncludeScript";
        private const string EmbeddedScriptFormat_itemClick =
            "<script type='text/javascript'>\n" +
            "  function itemClickFilter(s, e){ \n" +
            "    e.processOnServer = \n" +
            "      (e.item.GetImageUrl().indexOf('itdl.gif') != -1) || \n" +
            "      (e.item.GetImageUrl().indexOf('folder.gif') != -1); \n" +
            "  } \n" +
            "</script>\n";

        public ConfigureReport()
        {
            if (log.IsDebugEnabled)
                log.Debug("creating configure report");
            this.PreRender += new EventHandler(ClientScript_PreRender);
        }
        private void ClientScript_PreRender(object sender, System.EventArgs e)
        {
            if (log.IsDebugEnabled)
                log.Debug("handling client script prerender");

            //if (!isLicensed)
            //    return;

            if (!Page.IsClientScriptBlockRegistered(filterIncludeScriptKey))
            {
                Page.RegisterClientScriptBlock(filterIncludeScriptKey,
                EmbeddedScriptFormat_itemClick);
                //Page.RegisterClientScriptBlock(filterIncludeScriptKey2,
                //EmbeddedScriptFormat_buttonClick);
            }

            if (!Page.IsClientScriptBlockRegistered("winclose"))
            {
                Page.RegisterClientScriptBlock("winclose", "<script type='text/javascript'>function winclose(s, e){window.close();}</script>");
                //Page.RegisterClientScriptBlock(filterIncludeScriptKey2,
                //EmbeddedScriptFormat_buttonClick);
            }
        }


        int MAX_NUMBER_VARIABLES = 20;
        int NUMBER_VARS = 20;
        private int NUMBER_DATASOURCES = 6;
        // Constructor. 
        // ... 

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (log.IsDebugEnabled)
                log.Debug("Loading configure report.");

            try
            {
                // read in license from web.config
                ArrowUtils.InitializeArrow(string.Concat(Page.Request.PhysicalApplicationPath, "\\web.config"));
                isLicensed = true;
            }
            catch (LicenseException lex)
            {
                ArrowUtils.LogFatalException(log, lex);
                Controls.Add(new LiteralControl(string.Format("License error: {0}", lex.Message)));
                return;
            }

            try
            {
                if (log.IsDebugEnabled)
                    log.Debug("loading request strings");

                //IE correctly converts the URL to just variable=value&variable2=value2, 
                //in chrome it looks like variable=value&amp;variable2=value2. Need to test and get value either way.

                itemId = Request.QueryString["amp;ItemId"];
                if (itemId == null)
                {
                    itemId = Request.QueryString["ITEMID"];
                    itemUrl = Request.QueryString["ITEMURL"];
                    listId = Request.QueryString["LISTID"];
                    action = Request.QueryString["ACTION"];
                }
                else
                {
                    itemUrl = Request.QueryString["amp;ITEMURL"];
                    listId = Request.QueryString["amp;ListId"];
                    action = Request.QueryString["amp;ACTION"];
                }
                if (log.IsDebugEnabled)
                    log.DebugFormat("Loading configure report page with action: {0}", action);

                // if loaded with any null values, assume close
                //bugbug: I believe this is so that some menus can generate a close button/step
                if (itemId == null || itemUrl == null || listId == null)
                {
                    if (log.IsDebugEnabled)
                        log.Debug("Item objects null; loading close form");

                    closeButton = new ASPxButton();
                    closeButton.Text = "Close window";
                    closeButton.SetClientSideEventHandler("Click", "winclose");

                    ASPxLabel finished = new ASPxLabel();
                    finished.Text = "Close the window, or click the button to close the window";
                    this.Form.Controls.Add(finished);
                    this.Form.Controls.Add(closeButton);
                    return;
                }

                if (log.IsDebugEnabled)
                    log.Debug("Getting site info.");

                string siteGUID = SPContext.Current.Web.ID.ToString();

                string itemGUID = "";

                if (log.IsDebugEnabled)
                    log.Debug("Getting file from SharePoint.");

                SPFile item = ArrowUtils.getFileFromDocLib_usingID(ArrowUtils.getDocLibObject(siteGUID, listId), Int32.Parse(itemId));
                itemGUID = item.UniqueId.ToString();

                ViewState["TemplateSiteGUID"] = siteGUID;
                ViewState["TemplateDocLibGUID"] = listId;
                ViewState["TemplateGUID"] = itemGUID;
                ViewState["TemplateName"] = item.Name;
                ViewState["TemplateFolder"] = item.ParentFolder.UniqueId.ToString();

                if (log.IsDebugEnabled)
                    log.Debug("Scanning for template metrics.");

                Stream templateStream2 = ArrowUtils.GetSPFileStream(new Guid((string)ViewState["TemplateSiteGUID"]), new Guid((string)ViewState["TemplateGUID"]));
                if (log.IsDebugEnabled)
                    log.Debug("Template metrics loaded.");
                string itemFileExtension = ArrowUtils.getTemplateExtension(item.Name);
                if (log.IsDebugEnabled)
                    log.DebugFormat("itemFileExtension={0}", itemFileExtension);
                bool isRptDefExt = "reportdef".Equals(itemFileExtension) || "wrf".Equals(itemFileExtension);
                if (log.IsDebugEnabled)
                    log.DebugFormat("isRptDef={0}", isRptDefExt.ToString());
                ViewState["isRptDef"] = isRptDefExt;
                if (isRptDefExt)
                    ViewState["RptDefFullUrl"] = ArrowUtils.getFileNameFromGuid(item.UniqueId, SPContext.Current.Web.ID);
                // this big was written to make sure things like .png files couldn't get by this step
                //if (string.IsNullOrEmpty(tm2.AutoTagData) && !isRptDefExt)
                if (!isRptDefExt)
                {
                    bool isTemplateExtension = ArrowUtils.IsTemplateExtension(itemFileExtension);
                    if (!isTemplateExtension)
                    {
                        string errormsg = string.Format("The template, {0}, is invalid or not configured for use with Arrow.", item.Name);
                        Controls.Add(
                            new LiteralControl(
                                "<b><h2>Error: File is not properly configured for use as a Windward template </br>" +
                                "Use the Windward Arrow web parts to create a report definition.</h2> Error details: " +
                                errormsg + "</b>"));
                        return;
                    }
                    TemplateMetrics tm2 = null;
                    try
                    {
                        tm2 = Report.GetMetrics(templateStream2);
                    }
                    catch (Exception ex)
                    {
                        ArrowUtils.LogWarnException(log, ex);
                        this.Form.Controls.Add(
                            new LiteralControl(
                                "<b><h2>Error: File is not properly configured for use as a Windward template </br>" +
                                "Use the Windward Arrow web parts to create a report definition.</h2> Error details: " +
                                ex.Message.ToString() + "</b>"));
                        return;
                    }
                    if (action != "{ASSEMBLE}" && string.IsNullOrEmpty(tm2.AutoTagData) && tm2.Datasources.Length > 0)
                    {
                        string errormsg = string.Format("The template, {0}, contains tags but no data source profile. Please set the data sources in AutoTag or create a report definition.", item.Name);
                        Controls.Add(
                            new LiteralControl(
                                "<b><h2>Error: File is not properly configured for use as a Windward template </br>" +
                                "Use the Windward Arrow web parts to create a report definition.</h2> Error details: " +
                                errormsg + "</b>"));
                        return;
                    }
                    NUMBER_VARS = tm2.Vars.Length;
                    MAX_NUMBER_VARIABLES = NUMBER_VARS;
                    NUMBER_DATASOURCES = tm2.Datasources.Length;
                }

                if (action == "{ASSEMBLE}")
                {
                    if (log.IsDebugEnabled)
                    {
                        log.Debug("Handling assemble action.");
                        log.Debug("Loading controls.");
                    }

                    #region Assemble
                    if (ArrowUtils.getTemplateExtension(item.Name).Equals("reportdef") || ArrowUtils.getTemplateExtension(item.Name).Equals("wrf"))
                    {
                        closeButton = new ASPxButton();
                        closeButton.Text = "Close window";
                        closeButton.SetClientSideEventHandler("Click", "winclose");

                        ASPxLabel finished = new ASPxLabel();
                        finished.Width = Unit.Pixel(250);
                        finished.Text = "Cannot generate a report definition using a report definition file, try again with a report template.";
                        this.Form.Controls.Add(finished);
                        this.Form.Controls.Add(closeButton);
                        return;
                    }
                    wizzy = new Wizard();
                    wizzy.ID = "RptDefWizzy";
                    wizzy.Width = Unit.Pixel(WizzyWidth);
                    wizzy.Height = Unit.Pixel(WizzyHeight_assemble);
                    wizzy.StepStyle.VerticalAlign = VerticalAlign.Top;
                    //wizzy.StepStyle.ForeColor = Color.FromArgb(0x5D7B9D);
                    //wizzy.BackColor = Color.FromName("SlateBlue");
                    wizzy.BorderStyle = BorderStyle.None;
                    wizzy.BorderColor = Color.FromName("White");
                    wizzy.BorderWidth = 0;
                    wizzy.SideBarStyle.Width = 150;
                    wizzy.SideBarStyle.VerticalAlign = VerticalAlign.Top;
                    //wizzy.SideBarStyle.BackColor = Color.FromArgb(0x7C6F57);
                    //wizzy.SideBarButtonStyle.BackColor = Color.FromName("Black");
                    wizzy.NextButtonClick += new WizardNavigationEventHandler(wizzy_NextButtonClick_assemble);
                    wizzy.FinishButtonClick += new WizardNavigationEventHandler(wizzy_FinishButtonClick_assemble);
                    wizzy.DisplaySideBar = false;

                    Button tempButton = (Button)wizzy.FindControl("StepNavigationTemplateContainerID$StepNextButton");
                    tempButton.ValidationGroup = "validationGroup" + this.UniqueID;
                    tempButton.CausesValidation = true;
                    Button tempButton2 = (Button)wizzy.FindControl("StartNavigationTemplateContainerID$StartNextButton");
                    tempButton2.ValidationGroup = "validationGroup" + this.UniqueID;
                    tempButton2.CausesValidation = true;

                    for (int i = 0; i < 5; i++)
                    {
                        WizardStepBase newStep = new WizardStep();
                        newStep.ID = "Step" + (i).ToString();
                        newStep.Title = "Step" + (i).ToString();

                        newStep.Controls.Add(createTable_assemble(i));

                        wizzy.WizardSteps.Add(newStep);
                    }
                    wizzy.ActiveStepIndex = 1;
                    this.Form.Controls.Add(wizzy);

                    if (log.IsDebugEnabled)
                        log.Debug("Finished loading assemble controls.");
                    return;
                    #endregion
                }

                if (log.IsDebugEnabled)
                    log.Debug("Loading report definition from file.");
                ReportDefinition rai = null;
                string errorMessage = "";

                // the following try-catch ensures the rai will not be null
                try
                {
                    rai = ArrowUtils.GetReportDefFromFile(new Guid(siteGUID), new Guid(itemGUID), out errorMessage);
                    if (rai == null)
                        throw new Exception("The template's report definition is invalid or relies on a data source that is not available.");
                }
                catch (Exception exc)
                {
                    ArrowUtils.LogWarnException(log, exc);
                    this.Form.Controls.Add(
                        new LiteralControl(
                            "<b><h2>Error: File is not properly configured for use as a Windward template </br>" +
                            "Use the Windward Arrow web parts to create a report definition.</h2> Error details: " +
                            exc.Message.ToString() + "</b>"));
                    return;
                }

                //bugbug: why do we reset NUMBER_VARS and MAX_NUMBER_VARIABLES here? may be unnecessary
                NUMBER_VARS = rai.variableNameArray.Length;
                MAX_NUMBER_VARIABLES = NUMBER_VARS;

                Table vars = null;
                ViewState["Vars"] = "true";
                if (rai != null) //bugbug 12/16/10: above try-catch ensures rai!=null
                {
                    ViewState["TemplateName"] = rai.template;
                    ViewState["TemplateExtension"] = ArrowUtils.getTemplateExtension(rai.template);

                    //Pull the save location from RAI if it exists
                    if (!(rai.saveSPDocumentLib.Equals(rai.saveSPSite) && rai.saveSPWeb.Equals(rai.saveSPSite)))
                    {
                        if (log.IsDebugEnabled)
                            log.Debug("Loading default save location from report definition.");
                        ViewState["OutputDocLibGUID"] = rai.saveSPDocumentLib.ToString();
                        ViewState["OutputSiteGUID"] = rai.saveSPWeb.ToString();
                    }
                    if (action == "{HTML}")
                    {
                        if (log.IsDebugEnabled)
                            log.Debug("Handling view HTML action.");

                        #region HTML

                        DataDefinition[] rdsi = getRDSIFromRAI(rai);
                        string absolutePath = getAbsPathFromSPFile(ArrowUtils.GetSPFileFromDocLib((SPDocumentLibrary)ArrowUtils.getDocLibObject((string)ViewState["TemplateSiteGUID"],
                                                                         (string)ViewState["TemplateDocLibGUID"]), (string)ViewState["TemplateGUID"]));

                        string[] varValues = rai.variableDefaultArray;
                        string url = "";

                        //Generate a URL 
                        url = ArrowUtils.generateUrl(SPContext.Current.Web.Url, rai, absolutePath, RPT_HTML, varValues, null);
                        if (log.IsDebugEnabled)
                            log.DebugFormat("Redirecting to URL report at {0}", url);
                        Response.Redirect(url, true);
                        return;

                        #endregion
                    }
                    else if (action == "{PDF}")
                    {
                        if (log.IsDebugEnabled)
                            log.Debug("Handling view PDF action.");

                        #region PDF
                        DataDefinition[] rdsi = getRDSIFromRAI(rai);
                        string absolutePath = getAbsPathFromSPFile(ArrowUtils.GetSPFileFromDocLib((SPDocumentLibrary)ArrowUtils.getDocLibObject((string)ViewState["TemplateSiteGUID"],
                                                                         (string)ViewState["TemplateDocLibGUID"]), (string)ViewState["TemplateGUID"]));

                        string[] varValues = rai.variableDefaultArray;
                        string url = "";

                        //Generate a URL 
                        string id = "pdf";
                        url = ArrowUtils.generateUrl(SPContext.Current.Web.Url, rai, absolutePath, RPT_PDF, varValues, "report");
                        if (log.IsDebugEnabled)
                            log.Debug("Clearing response.");
                        Response.Clear();
                        if (log.IsDebugEnabled)
                            log.DebugFormat("Loading PDF iframe with {0}", url);
                        this.Form.Controls.Add(new LiteralControl("<iframe ID=\"" + id + "\" src=\"" + url + "\" runat=\"server\" width=\"100%\" height=\"860px\" frameborder=\"0\"> </iframe>"));
                        return;
                        #endregion
                    }
                    else if (action == "{INSTARUNPDF}")
                    {
                        if (log.IsDebugEnabled)
                            log.Debug("Handling insta-run PDF action");

                        #region instarunpdf
                        instaRun(rai, RPT_PDF);
                        #endregion
                    }
                    else if (action == "{INSTARUNDOCX}")
                    {
                        if (log.IsDebugEnabled)
                            log.Debug("Handling insta-run DOCX action");

                        #region instarundocx
                        instaRun(rai, RPT_DOCX);
                        #endregion
                    }
                    else if (action == "{INSTARUNXLSX}")
                    {
                        if (log.IsDebugEnabled)
                            log.Debug("Handling insta-run XLSX action.");

                        #region instarunxlsx
                        instaRun(rai, RPT_XLSX);
                        #endregion
                    }
                    else if (action == "{INSTARUNPPTX}")
                    {
                        if (log.IsDebugEnabled)
                            log.Debug("Handling insta-run PPTX action.");

                        #region instarunpptx
                        instaRun(rai, RPT_PPTX);
                        #endregion
                    }
                    else if (action == "{INSTARUN}")
                    {
                        if (log.IsDebugEnabled)
                            log.Debug("Determining which insta-run action to execute.");

                        #region instaRun
                        string templateExtension = ArrowUtils.getTemplateExtension(rai.template);
                        if (templateExtension.Equals("pptx"))
                        {
                            if (log.IsDebugEnabled)
                                log.Debug("Executing insta-run PPTX.");
                            instaRun(rai, RPT_PPTX);
                        }
                        else if (templateExtension.Equals("docx"))
                        {
                            if (log.IsDebugEnabled)
                                log.Debug("Executing insta-run DOCX.");
                            instaRun(rai, RPT_DOCX);
                        }
                        else if (templateExtension.Equals("xlsx"))
                        {
                            if (log.IsDebugEnabled)
                                log.Debug("Executing insta-run XLSX.");
                            instaRun(rai, RPT_XLSX);
                        }
                        #endregion
                    }
                    else if (action == "{SCHEDULE}")
                    {
                        if (log.IsDebugEnabled)
                            log.Debug("Loading controls for schedule.");

                        #region Schedule

                        // start over switch
                        hidStartOver = new HiddenField();
                        hidStartOver.Value = false.ToString();
                        this.Form.Controls.Add(hidStartOver);

                        // title & status
                        lblStatus = new Label();
                        resetStatus();
                        this.Form.Controls.Add(lblStatus);

                        #region Wizard-Style GUI

                        // add the schedule wizard
                        schedWizard = new Wizard();
                        schedWizard.BorderStyle = BorderStyle.Solid;
                        schedWizard.Width = Unit.Pixel(WizzyWidth);
                        schedWizard.Height = Unit.Pixel(WizzyHeight_schedule);
                        schedWizard.BorderStyle = BorderStyle.None;
                        schedWizard.BorderColor = Color.FromName("White");
                        schedWizard.BorderWidth = 0;
                        schedWizard.StartNextButtonText = "Next";
                        schedWizard.StepNextButtonText = "Next";
                        schedWizard.NextButtonClick += new WizardNavigationEventHandler(schedWizard_NextButtonClick);
                        schedWizard.StepPreviousButtonText = "Previous";
                        schedWizard.FinishPreviousButtonText = "Previous";
                        schedWizard.FinishCompleteButtonText = "Schedule Report";
                        //schedWizard.FinishCompleteButtonStyle.BackColor = Color.FromName("Orange");
                        schedWizard.FinishButtonClick += new WizardNavigationEventHandler(schedWizard_FinishButtonClick);
                        schedWizard.SideBarButtonClick += new WizardNavigationEventHandler(schedWizard_SideBarButtonClick);
                        schedWizard.PreviousButtonClick += new WizardNavigationEventHandler(schedWizard_PreviousButtonClick);
                        schedWizard.DisplaySideBar = false;

                        // parameter selection step
                        WizardStep parameterSelectionStep = new WizardStep();
                        parameterSelectionStep.ID = "GetParameters";
                        parameterSelectionStep.Title = "Parameter Selection";
                        parameterSelectionStep.Controls.Add((Control)(parmSelector = new ParameterValueSelector(new Guid((String)ViewState["TemplateSiteGUID"]), new Guid((String)ViewState["TemplateGUID"]))));
                        schedWizard.WizardSteps.Add(parameterSelectionStep);

                        // schedule selection step
                        WizardStep scheduleSelectionStep = new WizardStep();
                        scheduleSelectionStep.ID = "DoSchedule";
                        scheduleSelectionStep.Title = "Schedule the Report";
                        scheduleSelectionStep.Controls.Add(scheduleSelector = new ScheduleSelector());
                        // sched sel init here because it needs viewstate before event hdlrs
                        if (ViewState["reportName"] != null)
                            scheduleSelector.outName = (string)ViewState["reportName"];
                        if (ViewState["outputLibGuid"] != null)
                            scheduleSelector.outLibGuid = new Guid((string)ViewState["outputLibGuid"]);
                        if (ViewState["templateGuid"] != null)
                            scheduleSelector.tGuid = new Guid((string)ViewState["templateGuid"]);
                        if (ViewState["outputFormat"] != null)
                            scheduleSelector.outFmt = (string)ViewState["outputFormat"];
                        schedWizard.WizardSteps.Add(scheduleSelectionStep);

                        // output selection step
                        WizardStep outputSelectionStep = new WizardStep();
                        outputSelectionStep.ID = "OutputSelectionStep";
                        outputSelectionStep.Title = "Select Output";
                        //outputSelectionStep.Controls.Add((Control)(outputSelector = new MenuGridViewStyleOutputSelector()));
                        outputSelectionStep.Controls.Add((Control)(outputSelector = new OutputSelector()));
                        schedWizard.WizardSteps.Add(outputSelectionStep);

                        // review step
                        WizardStep reviewStep = new WizardStep();
                        reviewStep.ID = "ReviewStep";
                        reviewStep.Title = "Review Selections";
                        // this is how tabs do it
                        //addReviewControl(reviewStep);
                        // we probably want to parameterize this method or make
                        //createReviewWizardControls();
                        //schedWizard.WizardSteps.Add(reviewStep);
                        if (ArrowUtils.GetNumVarsForDisplay(rai) > 0)
                            schedWizard.ActiveStepIndex = 0;
                        else
                            schedWizard.ActiveStepIndex = 1;
                        this.Form.Controls.Add(schedWizard);

                        if (log.IsDebugEnabled)
                            log.Debug("Finished loading controls for schedule.");

                        #endregion Wizard-Style GUI
                        #endregion Schedule
                    }
                    else
                    {
                        if (log.IsDebugEnabled)
                            log.Debug("Handling Run Report action.");

                        #region RunAReport
                        Form.Controls.Add(createRunReportControls(rai));
                        #endregion
                    }
                }
                else
                {
                    log.Warn("unexpected rai=null");
                    if (log.IsDebugEnabled)
                        log.DebugFormat("Ending configure report page load. {0}", errorMessage);
                    Form.Controls.Add(new LiteralControl("<b><h2>Error: File is not properly configured for use as a Windward Template </br>" +
                                                                    "Use the Windward Arrow web parts to create a report definition.</h2></b>"));
                    Form.Controls.Add(new LiteralControl("</br>" + errorMessage));
                    return;
                }
            }
            catch (Exception ex)
            {
                ArrowUtils.LogFatalException(log, ex);
                Form.Controls.Clear();
                Form.Controls.Add(new LiteralControl(string.Format("There was an error loading the page: {0}", ex.Message)));
                return;
            }

            if (log.IsDebugEnabled)
                log.DebugFormat("Finished loading configure report page with action: {0}", action);
        }

        #region shared_member_functions

        /// <summary>
        /// Runs a report using the specified ReportDefinition and report output format.  The report is run using defaults
        /// from the ReportDefinition.
        /// </summary>
        /// <param name="rai"></param>
        /// <param name="outputFormat"></param>
        void instaRun(ReportDefinition rai, string outputFormat)
        {
            if (log.IsDebugEnabled)
                log.Debug("Insta-run started.");

            // get the save folder
            SPFolder saveFolder = null;
            if (!(rai.saveSPDocumentLib.Equals(rai.saveSPSite) && rai.saveSPWeb.Equals(rai.saveSPSite)))
            {
                // use rpt def default save location
                if (log.IsDebugEnabled)
                    log.Debug("Using default save location from report definition.");
                ViewState["OutputDocLibGUID"] = rai.saveSPDocumentLib.ToString();
                ViewState["OutputSiteGUID"] = rai.saveSPWeb.ToString();
                if (!(rai.saveSPFolder.Equals(rai.saveSPSite)))
                {
                    SPWeb saveWeb = ArrowUtils.getSPWeb(rai.saveSPWeb);
                    saveFolder = saveWeb.GetFolder(rai.saveSPFolder);
                }
            }
            else
            {
                // rpt def has no default save location; save to template (or rptDef?) location
                if (log.IsDebugEnabled)
                    log.Debug("Report definition has no default save location; using current folder.");
                ViewState["OutputDocLibGUID"] = ViewState["TemplateDocLibGUID"];
                ViewState["OutputSiteGUID"] = ViewState["TemplateSiteGUID"];
                SPWeb saveWeb = ArrowUtils.getSPWeb(new Guid((string)ViewState["OutputSiteGUID"]));
                saveFolder = saveWeb.GetFolder(new Guid((string)ViewState["TemplateFolder"]));
            }

            // get the data definition array
            if (log.IsDebugEnabled)
                log.Debug("Loading data definitions.");
            DataDefinition[] rdsi = getRDSIFromRAI(rai);

            // get default variable values
            if (log.IsDebugEnabled)
                log.Debug("Loading variables.");
            string[] varValues = rai.variableDefaultArray;
            
            // create the report name
            //bugbug
            string reportNameInsta;
            if (rai.reportName != null)
                reportNameInsta = rai.reportName;
            else
                reportNameInsta = "Report_of_" + rai.title;

            // generate the report
            if (log.IsDebugEnabled)
                log.Debug("Loading output document library.");
            SPDocumentLibrary outDocLib = ArrowUtils.getDocLibObject((string)ViewState["OutputSiteGUID"], (string)ViewState["OutputDocLibGUID"]);
            if (log.IsDebugEnabled)
                log.Debug("Generating report.");
            ArrowUtils.generateReport(rai, rdsi, outDocLib, reportNameInsta, outputFormat, varValues, saveFolder);
            if (log.IsDebugEnabled)
                log.Debug("Finished generating report.");
            
            // finish message label
            string finishMsg = string.Format(INSTA_FIN_MSG_FORMAT, outDocLib.Title, outDocLib.ParentWeb.Title);
            LiteralControl finishedLabel = new LiteralControl(finishMsg);

            // close button
            ASPxButton closeWindow = new ASPxButton();
            closeWindow.Text = "Close Window";
            closeWindow.SetClientSideEventHandler("Click", "winclose");
            
            // layout table
            Table layoutTable = ArrowUtils.createEmptyTable(2, 2, 40, 100);
            layoutTable.Rows[0].Cells[1].Controls.Add(finishedLabel);
            layoutTable.Rows[1].Cells[1].Controls.Add(closeWindow);

            this.Form.Controls.Add(layoutTable);
            if (log.IsDebugEnabled)
                log.Debug("Insta-run finished.");
        }


        #endregion

        
        #region memberfunction_RunReport

        /// <summary>
        /// This creates the controls for the standard Run a Report action.
        /// </summary>
        /// <param name="rai"></param>
        /// <returns></returns>
        private Table createRunReportControls(ReportDefinition rai)
        {
            if (log.IsDebugEnabled)
                log.Debug("Creating output controls for run report action.");

            Label variablesHeader = new Label();
            variablesHeader.Text = "Set the values for the following variables.";
            variablesHeader.ApplyStyle(ArrowUtils.headerStyle());
            variablesHeader.Width = Unit.Pixel(820);

            errorMessageVars_runreport = new ASPxLabel();
            errorMessageVars_runreport.Text = "";
            errorMessageVars_runreport.Visible = false;
            errorMessageVars_runreport.ApplyStyle(ArrowUtils.errorStyle());
            errorMessageVars_runreport.ForeColor = System.Drawing.Color.Red;

            int buffer = 0;
            int numVars = ArrowUtils.GetNumVarsForDisplay(rai);
            //if (rai.variableNameArray.Length > 0)
            if (numVars > 0)
            {
                runReportTable = ArrowUtils.makeTableAlternating(ArrowUtils.createEmptyTable(15, 1, 28, 152));
                runReportTable.Rows[0].Cells[0].Controls.Add(variablesHeader);
                runReportTable.Rows[1].Cells[0].Controls.Add(errorMessageVars_runreport);
                //runReportTable.Rows[2].Cells[0].Controls.Add(ArrowUtils.createVarTable_runreport(rai, NUMBER_VARS, out variableValueTextBoxArray_runreport, out variableValueDropDownListArray_runreport));
                runReportTable.Rows[2].Cells[0].Controls.Add(ArrowUtils.createVarTable_runreport(rai, numVars, out variableValueTextBoxArray_runreport, out variableValueDropDownListArray_runreport));
                runReportTable.Rows[2].CssClass = "";
                buffer = 3;
                buffer++;
            }
            else
            {
                runReportTable = ArrowUtils.makeTableAlternating(ArrowUtils.createEmptyTable(12, 1, 28, 152));
            }

            errorMessage_runreport = new ASPxLabel();
            errorMessage_runreport.Text = "";
            errorMessage_runreport.ClientVisible = false;
            errorMessage_runreport.ApplyStyle(ArrowUtils.errorStyle());
            errorMessage_runreport.ForeColor = System.Drawing.Color.Red;

            runReportHeader = new Label();
            runReportHeader.Text = "Select the report format and type.";
            runReportHeader.ApplyStyle(ArrowUtils.headerStyle());

            reportNameLabel = new Label();
            reportNameLabel.Text = "1. Report name:";

            reportName = new ASPxTextBox();
            reportName.Width = ArrowUtils.DEFAULT_TXTBX_WIDTH;
            //reportName.Native = true;

            if (ViewState["ReportName"] != null && ((string)ViewState["ReportName"]).Length > 0)
            {
                reportName.Text = (string)ViewState["ReportName"];
            }
            reportName.ValueChanged += reportName_ValueChanged;

            Label outputFormatLabel = new Label();
            outputFormatLabel.Text = "2. Select the report format.";

            Label outputTypeLabel = new Label();
            outputTypeLabel.Text = "3. How should the report be generated?";

            ASPxRadioButton genUrl = new ASPxRadioButton();
            genUrl.Text = "Generate a URL";
            genUrl.GroupName = "typeSelect";
            genUrl.ID = "url";
            genUrl.AutoPostBack = true;
            genUrl.ValueChanged += radio_valueChanged;
            ASPxRadioButton report = new ASPxRadioButton();
            report.Text = "Save to a Document Library";
            report.GroupName = "typeSelect";
            report.ID = "report";
            report.AutoPostBack = true;
            report.ValueChanged += radio_valueChanged;

            selDocLibLabel = new Label();
            selDocLibLabel.Text = "4. Pick a document library: Use the dropdown menu below.";
            selDocLibLabel.Visible = false;

            // output folder selector
            outputFolderSelector = new SPFileSelector(SPFileSelector.Mode.Folder);
            outputFolderSelector.Visible = false;

            closeButton = new ASPxButton();
            closeButton.Text = "Close Window";
            closeButton.SetClientSideEventHandler("Click", "winclose");
            closeButton.Visible = false;

            generateButton = new ASPxButton();
            generateButton.Text = "Generate";
            //generateButton.Native = true;
            generateButton.Click += finishButton_Click;

            finalLiteral = new LiteralControl();
            finalLiteral.Visible = false;

            runReportOutputList = new DropDownList();
            string pptx = "pptx";
            ViewState["OutputFormat"] = RPT_PDF;
            if (pptx.Equals(ViewState["TemplateExtension"]))
            {
                runReportOutputList.Items.Add(new ListItem("PDF", RPT_PDF));
                runReportOutputList.Items.Add(new ListItem("PPTX", RPT_PPTX));
            }
            else
            {
                runReportOutputList.Items.Add(new ListItem("PDF", RPT_PDF));
                runReportOutputList.Items.Add(new ListItem("DOCX", RPT_DOCX));
                runReportOutputList.Items.Add(new ListItem("Word 2003 XML", RPT_WML));
                runReportOutputList.Items.Add(new ListItem("RTF", RPT_RTF));
                runReportOutputList.Items.Add(new ListItem("Excel 2003 XML", RPT_SML));
                runReportOutputList.Items.Add(new ListItem("XLS", RPT_XLS));
                runReportOutputList.Items.Add(new ListItem("XLSX", RPT_XLSX));
                runReportOutputList.Items.Add(new ListItem("HTML", RPT_HTML));
            }


            runReportTable.Rows[0 + buffer].Cells[0].Controls.Add(runReportHeader);
            runReportTable.Rows[1 + buffer].Cells[0].Controls.Add(errorMessage_runreport);
            runReportTable.Rows[2 + buffer].Cells[0].Controls.Add(reportNameLabel);
            runReportTable.Rows[3 + buffer].Cells[0].Controls.Add(reportName);

            runReportTable.Rows[4 + buffer].Cells[0].Controls.Add(outputFormatLabel);
            runReportTable.Rows[5 + buffer].Cells[0].Controls.Add(runReportOutputList);

            runReportTable.Rows[4 + buffer].Cells[0].Controls.Add(outputFormatLabel);
            runReportTable.Rows[5 + buffer].Cells[0].Controls.Add(runReportOutputList);

            runReportTable.Rows[6 + buffer].Cells[0].Controls.Add(outputTypeLabel);
            runReportTable.Rows[7 + buffer].Cells[0].Controls.Add(genUrl);
            runReportTable.Rows[7 + buffer].Cells[0].Controls.Add(report);

            runReportTable.Rows[8 + buffer].Cells[0].Controls.Add(selDocLibLabel);
            runReportTable.Rows[9 + buffer].Cells[0].Controls.Add(outputFolderSelector);

            runReportTable.Rows[10 + buffer].CssClass = "";
            runReportTable.Rows[10 + buffer].Cells[0].HorizontalAlign = HorizontalAlign.Center;
            runReportTable.Rows[10 + buffer].Cells[0].Controls.Add(new LiteralControl("<br>"));
            if (rai.variableTypeArray.Length == 0)
            {
                //add in some extra white space to push the generate button down.
                runReportTable.Rows[10 + buffer].Cells[0].Controls.Add(new LiteralControl("<br>"));
                runReportTable.Rows[10 + buffer].Cells[0].Controls.Add(new LiteralControl("<br>"));
                runReportTable.Rows[10 + buffer].Cells[0].Controls.Add(new LiteralControl("<br>"));
                runReportTable.Rows[10 + buffer].Cells[0].Controls.Add(new LiteralControl("<br>"));
                runReportTable.Rows[10 + buffer].Cells[0].Controls.Add(new LiteralControl("<br>"));
                runReportTable.Rows[10 + buffer].Cells[0].Controls.Add(new LiteralControl("<br>"));
                runReportTable.Rows[10 + buffer].Cells[0].Controls.Add(new LiteralControl("<br>"));
                runReportTable.Rows[10 + buffer].Cells[0].Controls.Add(new LiteralControl("<br>"));
                runReportTable.Rows[10 + buffer].Cells[0].Controls.Add(new LiteralControl("<br>"));
            }
            runReportTable.Rows[10 + buffer].Cells[0].Controls.Add(generateButton);
            runReportTable.Rows[10 + buffer].Cells[0].Controls.Add(closeButton);
            runReportTable.Rows[10 + buffer].Cells[0].Controls.Add(new LiteralControl("<br>"));
            runReportTable.Rows[10 + buffer].Cells[0].Controls.Add(finalLiteral);

            if (log.IsDebugEnabled)
                log.Debug("Finished creating output controls for run report action.");

            return runReportTable;
        }

        private void CreateDocLibSelector(ASPxMenu menu)
        {
            DevExpress.Web.ASPxMenu.MenuItem root = new DevExpress.Web.ASPxMenu.MenuItem();
            root.Text = "Select a document library";
            root.Image.Url = string.Format("{0}/_layouts/images/menu1.gif", SPContext.Current.Web.Url);
            menu.Items.Add(root);

            // get sorted collection of webs
            SPWebCollection collWebsite = ArrowUtils.GetSPWebCollectionFromCurrentSite();
            ArrayList sortedWebs = new ArrayList(collWebsite.Count);
            foreach (SPWeb oWebsite in collWebsite)
            {
                sortedWebs.Add(oWebsite);
            }
            sortedWebs.Sort(new ArrowUtils.SPWebSortComparer());

            // create submenu item for each web
            foreach (SPWeb oWebsite in sortedWebs)
            {
                root.Items.Add(createSiteMenuItem(oWebsite));
            }

        }
        
        private ReportDefinition getRAIFromViewState()
        {
            string errorMessage = "";
            ReportDefinition rai = ArrowUtils.GetReportDefFromFile(new Guid((string)ViewState["TemplateSiteGUID"]),
                                                                   new Guid((string)ViewState["TemplateGUID"]), out errorMessage);
            return rai;
        }
        
        private DataDefinition[] getRDSIFromRAI(ReportDefinition rai)
        {
            return rai.getDataSources();
        }
        
        private string getAbsPathFromSPFile(SPFile file)
        {
            return ArrowUtils.getAbsPathFromSPFile(file);
        }
        
        private string[] createVariableValuesArray(ReportDefinition rai, TextBox[] variableValueTextBoxArray, DropDownList[] variableValueDropDownListArray)
        {
            int numVars = ArrowUtils.GetNumVarsForDisplay(rai);
            string[] variableValues = new string[numVars];

            for (int i = 0; i < numVars; i++)
            {
                if (variableValueDropDownListArray[i].SelectedValue != null && variableValueDropDownListArray[i].SelectedValue.Length > 0)
                    variableValues[i] = variableValueDropDownListArray[i].SelectedValue.ToString();
                else
                    variableValues[i] = variableValueTextBoxArray[i].Text;
            }
            return variableValues;
        }
        
        /// <summary>
        /// <para>Must set:</para>
        /// <para>ViewState["ReportName"]</para>
        /// <para>ViewState["OutputFormat"]</para>
        /// <para>ViewState["OutputDestination"]</para>
        /// </summary>
        /// <param name="error"></param>
        /// <returns></returns>
        bool runReportValidation(out string error, SPFileSelectorFolderInfo outFolderInfo)
        {
            error = "Error:";
            bool toReturn = true;
            if (ViewState["ReportName"] == null)
            {
                error += "Report name not set; \n";
                toReturn = false;
            }
            if (ViewState["OutputFormat"] == null)
            {
                error += "Output format not selected; \n";
                toReturn = false;
            }
            if (!"URL".Equals(ViewState["OutputDestination"])
                && (ViewState["OutputSiteGUID"] == null || ViewState["OutputDocLibGUID"] == null))
            {
                error += "Output location not set; \n";
                if (!outFolderInfo.IsSPFolder)
                    error += "The selected output location is a website; \n";
                toReturn = false;
            }
            if ("HTML".Equals(ViewState["OutputFormat"]) && !(ViewState["OutputDestination"].Equals("URL")))
            {
                //If report format is HTML and going to a doc lib, inform user this is not possible at the moment
                error +=
                    "Outputting to HTML into a document library is currently not supported; try another format or create a URL instead";
                toReturn = false;
            }
            return toReturn;
        }
        
        /// <summary>
        /// Handles the finish button click event for generating a report.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void finishButton_Click(object sender, EventArgs e)
        {
            if (log.IsDebugEnabled)
                log.Debug("handling finish button clicked");

            // get selected output folder info
            SPFileSelectorFolderInfo outFolderInfo = outputFolderSelector.SelectedFolder;
            if (!"URL".Equals(ViewState["OutputDestination"]))
            {
                ViewState["OutputSiteGUID"] = outFolderInfo.WebGuid;
                ViewState["OutputDocLibGUID"] = outFolderInfo.LibGuid;
                ViewState[VS_FOLDR_OUT_GUID] = outFolderInfo.Guid;
                ViewState["OutputDestination"] = ArrowUtils.BuildFolderPathDisplayString(outFolderInfo);
            }

            string errormsg = "";
            if (runReportValidation(out errormsg, outFolderInfo))
            {
                errorMessage_runreport.ClientVisible = false;
                ReportDefinition rai = getRAIFromViewState();
                DataDefinition[] rdsi = getRDSIFromRAI(rai);
                Guid templWebGuid = new Guid((string)ViewState[VS_TEMPL_SITE_GUID]);
                Guid templateGuid = new Guid((string)ViewState[VS_TEMPL_GUID]);
                SPFile template = ArrowUtils.GetSPFileFromSPWeb(templWebGuid, templateGuid);
                string templateAbsPath = getAbsPathFromSPFile(template);

                string[] varValues = createVariableValuesArray(rai, variableValueTextBoxArray_runreport, variableValueDropDownListArray_runreport);
                string reportUrl;
                //bugbug: quick fix for output format always pdf bug
                ViewState["OutputFormat"] = runReportOutputList.SelectedValue;
                if (((string)ViewState["OutputDestination"]).Equals("URL"))
                {
                    //Generate a URL 
                    string url = ArrowUtils.generateUrl(SPContext.Current.Web.Url, rai, templateAbsPath,
                                                        (string)ViewState["OutputFormat"], varValues, (String)ViewState["ReportName"]);
                    reportUrl = ArrowUtils.makeURL("Report URL Link", url);
                }
                else
                {
                    // check if html - not supported for output to doc lib
                    if ("html".Equals((string)ViewState["OutputFormat"], StringComparison.OrdinalIgnoreCase))
                    {
                        errormsg = "Outputting to HTML in a document library is not supported; try another format, or choose to generate a URL instead.";
                        errorMessage_runreport.Text = errormsg;
                        errorMessage_runreport.ClientVisible = true;
                        return;
                    }

                    //Generate a Report
                    SPDocumentLibrary docLib = ArrowUtils.getDocLibObject((string)ViewState["OutputSiteGUID"],
                                                                            (string)ViewState["OutputDocLibGUID"]);
                    Guid outWebGuid = new Guid((string)ViewState[VS_OUT_SITE_GUID]);
                    SPWeb outWeb = ArrowUtils.GetSPWebCollectionFromCurrentSite()[outWebGuid];
                    string sFolderOutGuid = (string)ViewState[VS_FOLDR_OUT_GUID];
                    SPFolder outFolder = null;
                    if (!string.IsNullOrEmpty(sFolderOutGuid))
                    {
                        Guid outFolderGuid = new Guid(sFolderOutGuid);
                        outFolder = outWeb.GetFolder(outFolderGuid);
                    }

                    string reportPath = ArrowUtils.generateReport(rai, rdsi, docLib, (string)ViewState["ReportName"],
                                                                    (string)ViewState["OutputFormat"],
                                                                    varValues, outFolder);
                    reportUrl = ArrowUtils.makeURL("Link to Report in Document Library", reportPath);
                }
                generateButton.Visible = false;
                closeButton.Visible = true;
                finalLiteral.Text = reportUrl;
                finalLiteral.Visible = true;
            }
            else
            {
                errorMessage_runreport.Text = errormsg;
                errorMessage_runreport.ClientVisible = true;
            }
        }

        private DevExpress.Web.ASPxMenu.MenuItem createSiteMenuItem(SPWeb site)
        {
            DevExpress.Web.ASPxMenu.MenuItem siteMenu = new DevExpress.Web.ASPxMenu.MenuItem();
            siteMenu.Text = site.Title.ToString();
            siteMenu.DataItem = site;
            siteMenu.Image.Url = string.Format("{0}/_layouts/images/logo.gif", SPContext.Current.Web.Url);

            foreach (SPList list in site.Lists)
            {
                if (list is SPDocumentLibrary && !list.Hidden)
                {
                    siteMenu.Items.Add(createDocLibMenuItem(list));
                    siteMenu.DataItem = site;
                }
            }

            return siteMenu;
        }
        
        private DevExpress.Web.ASPxMenu.MenuItem createDocLibMenuItem(SPList list)
        {
            DevExpress.Web.ASPxMenu.MenuItem docLibItem = new DevExpress.Web.ASPxMenu.MenuItem();
            docLibItem.Text = list.Title;
            docLibItem.DataItem = list; docLibItem.Image.Url = string.Format("{0}/_layouts/images/itdl.gif", SPContext.Current.Web.Url);

            foreach (SPListItem folderListItem in list.Folders)
            {
                SPFolder folder = folderListItem.Folder;
                if (folder != null)
                    docLibItem.Items.Add(CreateFolderMenuItem(folder));
            }

            return docLibItem;
        }

        private static DevExpress.Web.ASPxMenu.MenuItem CreateFolderMenuItem(SPFolder folder)
        {
            DevExpress.Web.ASPxMenu.MenuItem folderItem = new DevExpress.Web.ASPxMenu.MenuItem();
            folderItem.Text = folder.Name;
            folderItem.DataItem = folder;
            folderItem.Image.Url = string.Format("{0}/_layouts/images/folder.gif", SPContext.Current.Web.Url);

            foreach (SPFolder subFolder in folder.SubFolders)
            {
                folderItem.Items.Add(CreateFolderMenuItem(subFolder));
            }

            return folderItem;
        }

        void reportName_ValueChanged(object o, EventArgs e)
        {
            if (log.IsDebugEnabled)
                log.Debug("handling report name changed");

            ASPxTextBox sender = (ASPxTextBox)o;
            ViewState["ReportName"] = ArrowUtils.trim(sender.Text);
            HttpContext.Current.Cache["ReportName_Global"] = ArrowUtils.trim(sender.Text);

        }

        void radio_valueChanged(object o, EventArgs e)
        {
            if (log.IsDebugEnabled)
                log.Debug("handling radio value changed");

            ASPxRadioButton sender = (ASPxRadioButton)o;
            if (sender.Checked && sender.ID.Equals("url"))
            {
                outputFolderSelector.Visible = false;
                selDocLibLabel.Visible = false;
                ViewState["OutputDestination"] = "URL";
            }
            if (sender.Checked && sender.ID.Equals("report"))
            {
                outputFolderSelector.Visible = true;
                selDocLibLabel.Visible = true;
                ViewState["OutputDestination"] = "DocLib";
            }
        }

        #endregion memberfunction_RunReport


        /// <summary>
        /// Generates the content of the review control.
        /// </summary>
        private void populateReviewContent(Control _reviewControl, IOutputSelector _outputSelector, ScheduleSelector _scheduleSelector)
        {
            // generate review tab content
            // assembly
            Label lblAsmVal = (Label)_reviewControl.FindControl("lblAsmVal");
            string asmStr = null;
            if (!string.IsNullOrEmpty((string)ViewState["TemplateSiteGUID"]))
                asmStr = ArrowUtils.getFileNameFromGuid(
                     new Guid((string)ViewState["TemplateGUID"]),
                     new Guid((string)ViewState["TemplateSiteGUID"]));
            if (asmStr == null || asmStr.LastIndexOf('/') < 0)
                asmStr = "None selected";
            else
            {
                asmStr = asmStr.Substring(asmStr.LastIndexOf('/') + 1);
                asmStr = "SITE NAME" + " > " + asmStr;
            }
            lblAsmVal.Text = asmStr;

            // variables

            // schedule
            Label lblDateVal = (Label)_reviewControl.FindControl("lblDateVal");
            try
            {
                string sDate = "";
                string sTime = "";
                sDate = _scheduleSelector.StartDateTime.Date.ToLongDateString();
                sTime = _scheduleSelector.StartDateTime.ToLongTimeString();
                lblDateVal.Text = "Starting " + sDate + " @ " + sTime + "\n" + SchedulerWebPart.getRecurranceString(_scheduleSelector);

            }
            catch (FormatException fe)
            {
                lblDateVal.Text = "None selected";
            }
            //bugbug: add recurrance string; probably need a whole helper method for this

            // report name
            Label lblOutNameVal = (Label)_reviewControl.FindControl("lblOutNameVal");
            if (ViewState["reportName"] != null && (string)ViewState["reportName"] != string.Empty)
                lblOutNameVal.Text = (string)ViewState["reportName"];
            else
                lblOutNameVal.Text = "None selected";

            // report format
            Label lblOutFmtVal = (Label)_reviewControl.FindControl("lblOutFmtVal");
            if (ViewState["outputFormat"] != null)
                lblOutFmtVal.Text = (string)ViewState["outputFormat"];
            else
                lblOutFmtVal.Text = "None selected";

            // report destination
            Label lblDestVal = (Label)_reviewControl.FindControl("lblDestVal");
            if (ViewState["outputLibGuid"] != null)
                lblDestVal.Text = _outputSelector.OutLibSiteTitle + " > " + (string)ViewState["outputLibName"];
            else
                lblDestVal.Text = "None selected";

            // email to
            Label lblEmailVal = (Label)_reviewControl.FindControl("lblEmailVal");
            if (ViewState["emailTo"] != null && (string)ViewState["emailTo"] != string.Empty)
                lblEmailVal.Text = (string)ViewState["emailTo"];
            else
                lblEmailVal.Text = "None selected";
        }

        void schedWizard_FinishButtonClick(object sender, WizardNavigationEventArgs e)
        {
            if (log.IsDebugEnabled)
                log.Debug("handling finish button click");

            if (hidStartOver.Value.Equals(true.ToString()))
            {

                schedWizard.Visible = false;
                closeButton = new ASPxButton();
                closeButton.Text = "Close Window";
                closeButton.SetClientSideEventHandler("Click", "winclose");

                ASPxLabel finished = new ASPxLabel();
                finished.Text = "Success. Close the window, or click the button to close the window";
                this.Form.Controls.Add(finished);
                this.Form.Controls.Add(closeButton);

                /*
                schedWizard.Visible = false;
                Panel reviewContent = new Panel();
                this.Form.Controls.Add(SchedulerWebPart.makeReviewControl(reviewContent));
                populateReviewContent(reviewContent, outputSelector, scheduleSelector);
                this.Form.Controls.Add(closeButton);
                 * */

            }
            if (hidStartOver.Value != null && hidStartOver.Value.Equals(true.ToString()))
            {
                // start over
                Context.Response.Redirect(Context.Request.Path);
            }

            scheduleReport();

        }
        void schedWizard_PreviousButtonClick(object sender, WizardNavigationEventArgs e)
        {
            if (log.IsDebugEnabled)
                log.Debug("handling prev button click");

            schedWizard_NextButtonClick(sender, e);
        }

        /// <summary>
        /// Does some validation and initialization tasks when advancing a step.
        /// Same as schedWizard_nextButtonClick
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void schedWizard_SideBarButtonClick(object sender, WizardNavigationEventArgs e)
        {
            if (log.IsDebugEnabled)
                log.Debug("handling sidebar click");

            schedWizard_NextButtonClick(sender, e);
        }

        /// <summary>
        /// Does some validation and initialization tasks when advancing a step.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void schedWizard_NextButtonClick(object sender, WizardNavigationEventArgs e)
        {
            if (log.IsDebugEnabled)
                log.Debug("handling next button click");

            ReportDefinition rai = getRAIFromViewState();

            switch (e.CurrentStepIndex)
            {
                case STEP_PARAMETER_SELECTION:/* parameter value selection */
                    if (log.IsDebugEnabled)
                        log.Debug("moving from parameter selection step");
                    UpdateViewStateVariables();
                    break;
                case STEP_SCHEDULE_SELECTION:/* schedule selection */
                    if (log.IsDebugEnabled)
                        log.Debug("moving from schedule selection step");
                    UpdateViewStateVariables();
                    break;
                case STEP_OUTPUT_SELECTION: /* output selection */
                    if (log.IsDebugEnabled)
                        log.Debug("moving from output selection step");
                    UpdateViewStateVariables();
                    break;
                case STEP_REVIEW: /* review step */
                    if (log.IsDebugEnabled)
                        log.Debug("moving from review step");
                    UpdateViewStateVariables();
                    break;
                default:
                    Exception ex = new Exception("Invalid Wizard Step: " + e.CurrentStepIndex.ToString());
                    ArrowUtils.LogFatalException(log, ex);
                    throw ex;
            }
        }
        private void UpdateViewStateVariables()
        {
            ViewState["emailTo"] = outputSelector.EmailTo;
            ViewState["outLibSiteTitle"] = outputSelector.OutLibSiteTitle;
            ViewState["outputFormat"] = outputSelector.ReportFormat;
            ViewState["outputLibGuid"] = outputSelector.OutputLibraryGuid;
            ViewState["outputLibName"] = outputSelector.OutputLibraryName;
            ViewState["reportName"] = outputSelector.ReportName;
            ViewState["rptAsmSiteTitle"] = (string)ViewState["TemplateName"];
        }
        /// <summary>
        /// Resets the status label. "<h1>Schedule A Report: Ready</h1>"
        /// </summary>
        private void resetStatus()
        {
            //lblStatus.Text = "<h1>Schedule A Report: Ready</h1>";
            lblStatus.Text = string.Empty;
        }
        /// <summary>
        /// Schedules a report using all of the specified values in the web part.
        /// </summary>
        private void scheduleReport()
        {
            resetStatus();

            // validation
            try
            {
                DateTime testDateTime = scheduleSelector.StartDateTime;
            }
            catch (FormatException fex)
            {
                addStatusError("Invalid date or time.&nbsp;" + fex.Message);
                //schedWizard.ActiveStepIndex = STEP_SCHEDULE_SELECTION; // back to select a different time
                return;
            }

            // various inputs
            DateTime startDateTime = scheduleSelector.StartDateTime;
            string reportTitle = outputSelector.ReportName;
            //bugbugbugbugbug
            int reportFormat = (int)SchedulerWebPart.reportTypeFromString(outputSelector.ReportFormat);
            Guid outLibGuid;
            try
            {
                outLibGuid = new Guid(outputSelector.OutputLibraryGuid);
            }
            catch (ArgumentNullException anex)
            {
                addStatusError("Invalid output library selection.");
                return;
            }
            Guid outSiteGuid = new Guid(outputSelector.OutLibSiteGuid);
            SPWeb saveWeb = ArrowUtils.getSPWeb(outSiteGuid);
            SPDocumentLibrary outLib = ArrowUtils.getDocLibObject(outSiteGuid, outLibGuid);
            string outSiteUrl = saveWeb.Url;
            string outFolderUrl = string.Format("{0}/{1}", outSiteUrl, outLib.RootFolder.Url);
            if (!string.IsNullOrEmpty(outputSelector.OutputFolderGuid))
            {
                Guid saveFolderGuid = new Guid(outputSelector.OutputFolderGuid);
                SPFolder saveFolder = saveWeb.GetFolder(saveFolderGuid);
                outFolderUrl = string.Format("{0}/{1}", outSiteUrl, saveFolder.Url);
            }
            string emailTo = outputSelector.EmailTo;
            Guid templateGuid = scheduleSelector.tGuid; //bugbug: this seems to have lost its meaning here; get zero GUID

            // get template or report assembly file name
            string templateOrRptAsmFileName;
            Guid rptAsmGuid = new Guid((string)ViewState["TemplateGUID"]);
            if ((bool)ViewState["isRptDef"])
                templateOrRptAsmFileName = (string)ViewState["RptDefFullUrl"];
            else
                templateOrRptAsmFileName = (string)ViewState["TemplateName"];

            #region create a ScheduleItem
            ScheduleManager schedMgr = new ScheduleManager();
            //ScheduleManager.IsArrow = true;
            ScheduleItem schedItem = new ScheduleItem();
            schedItem.EmailTo = emailTo;
            schedItem.Format = (Report.REPORT_TYPE)reportFormat;
            schedItem.SaveFolder = outFolderUrl;
            schedItem.SiteUrl = SPContext.Current.Web.Url;
            schedItem.System = "arrow 3";
            schedItem.TemplateFileName = templateOrRptAsmFileName;
            schedItem.Title = reportTitle;
            schedItem.DataProfileGuid = string.Empty;
            schedItem.IsRptAsm = true;
            schedItem.SaveSiteUrl = ArrowUtils.getSPWeb(outSiteGuid).Url;

            // get the schedule period
            SchedulePeriod schedInfo = null;
            try
            {
                schedInfo = scheduleSelector.ScheduleInfo;
            }
            catch (WeeklyRecurSelException wex)
            {
                addStatusError("Invalid weekly recurrance selection");
                return;
            }
            SPUser user = SPContext.Current.Web.CurrentUser;
            if (user.RegionalSettings != null)
            {
                SPTimeZone userTimeZone = user.RegionalSettings.TimeZone;
                DateTime utcStartDateTime = userTimeZone.LocalTimeToUTC(startDateTime);
                DateTime serverLocalStartDateTime = utcStartDateTime.ToLocalTime();
                schedInfo.RunTime = serverLocalStartDateTime;
            }
            else
                schedInfo.RunTime = startDateTime;
            schedInfo.RunZone = TimeZoneInfo.Local;
            schedItem.Period = schedInfo;
            schedItem.CalculateRunNext();
            #endregion create a ScheduleItem

            // add the parameters
            string sSiteGuid = (string)ViewState["TemplateSiteGUID"];
            ScheduleVarItemCollection theVars = parmSelector.getVars(new Guid(sSiteGuid), rptAsmGuid);
            foreach (ScheduleVarItem var in theVars)
                schedItem.Variables.Add(var);

            // plug schedule item into the scheduler db
            schedMgr.Insert(schedItem);

            // set start over button
            hidStartOver.Value = true.ToString();
            schedWizard.FinishCompleteButtonText = "Close Window";
        }
        /// <summary>
        /// Adds the string head + msg + tail to the lblStatus
        /// </summary>
        /// <param name="head"></param>
        /// <param name="tail"></param>
        /// <param name="msg"></param>
        private void addStatusError(string msg)
        {
            lblStatus.Text += ERROR_HEADER + msg + ERROR_TAIL;
        }
        #region memberfunctions_Assemble
        void menuOutLibItemClick_assemble(object sender, MenuItemEventArgs e)
        {
            if (log.IsDebugEnabled)
                log.Debug("handling menu out lib click");

            DevExpress.Web.ASPxMenu.MenuItem libItem = (DevExpress.Web.ASPxMenu.MenuItem)e.Item;

            // just rebind if the item doesn't contain docs
            if (!(libItem.DataItem is SPDocumentLibrary) &&
                !(libItem.DataItem is SPFolder))
            {
                return;
            }

            // get the web, doc lib, and folder (if any)
            SPWeb web = null;
            SPFolder folder = null;
            SPDocumentLibrary docLib = null;
            if (libItem.DataItem is SPDocumentLibrary)
            {
                docLib = (SPDocumentLibrary)libItem.DataItem;
                web = docLib.ParentWeb;
                ViewState[VS_FOLDR_OUT_GUID] = null;
            }
            else
            {
                folder = (SPFolder)libItem.DataItem;
                web = folder.ParentWeb;
                ViewState[VS_FOLDR_OUT_GUID] = folder.UniqueId.ToString();
                string strDocLibGUID = folder.ParentListId.ToString();
                docLib = ArrowUtils.getDocLibObject(web.ID.ToString(), strDocLibGUID);
            }

            ViewState["OutputDocLibGUID"] = docLib.ID.ToString();
            ViewState[VS_OUT_SITE_GUID] = web.ID.ToString();


            String selectionMessage = web.Title + " -> " + docLib.Title;
            ViewState["OutputDestination"] = selectionMessage;
            //DocLibSelection.Text = selectionMessage;


            //if (!DocLibSelection.Visible)
            //{
            //    DocLibSelection.Visible = true;
            //}
        }
        void menuRptOutLocItemClick_assemble(object sender, MenuItemEventArgs e)
        {
            if (log.IsDebugEnabled)
                log.Debug("handling report output location menu item click");

            DevExpress.Web.ASPxMenu.MenuItem libItem = (DevExpress.Web.ASPxMenu.MenuItem)e.Item;

            // just rebind if the item doesn't contain docs
            if (!(libItem.DataItem is SPDocumentLibrary) &&
                !(libItem.DataItem is SPFolder))
            {
                return;
            }

            // get the web, doc lib, and folder (if any)
            SPWeb web = null;
            SPFolder folder = null;
            SPDocumentLibrary docLib = null;
            if (libItem.DataItem is SPDocumentLibrary)
            {
                docLib = (SPDocumentLibrary)libItem.DataItem;
                web = docLib.ParentWeb;
                ViewState[VS_RPT_OUT_FOLDR_GUID] = docLib.RootFolder.UniqueId.ToString();
            }
            else
            {
                folder = (SPFolder)libItem.DataItem;
                web = folder.ParentWeb;
                ViewState[VS_RPT_OUT_FOLDR_GUID] = folder.UniqueId.ToString();
                string strDocLibGUID = folder.ParentListId.ToString();
                docLib = ArrowUtils.getDocLibObject(web.ID.ToString(), strDocLibGUID);
            }

            ViewState["ReportOutputDocLibGUID"] = docLib.ID.ToString();
            ViewState["ReportOutputSiteGUID"] = web.ID.ToString();


            String selectionMessage = web.Title + " -> " + docLib.Title;
            ViewState["ReportOutputDestination"] = selectionMessage;
            //reportOutputSel.Text = selectionMessage;

            Style headerStyle = new Style();
            headerStyle.Font.Name = "Verdana";
            headerStyle.Font.Size = FontUnit.Parse("12pt");



            //if (!reportOutputSel.Visible)
            //{
            //    reportOutputSel.Visible = true;
            //}
        }
        private Table createOverview_assemble()
        {
            if (log.IsDebugEnabled)
                log.Debug("Creating overview step for assemble.");

            Label s1 = new Label();
            Label s2 = new Label();
            Label s3 = new Label();
            Label s4 = new Label();
            //s1.ApplyStyle(normalBoldStyle);
            //s2.ApplyStyle(normalBoldStyle);
            //s3.ApplyStyle(normalBoldStyle);
            //s4.ApplyStyle(normalBoldStyle);

            s1.Text = "Step 1:";
            s2.Text = "Step 2:";
            s3.Text = "Step 3:";
            s4.Text = "Review:";
            s1.CssClass = ArrowUtils.css_pageTitle();
            s2.CssClass = ArrowUtils.css_pageTitle();
            s3.CssClass = ArrowUtils.css_pageTitle();
            s4.CssClass = ArrowUtils.css_pageTitle();

            ASPxImage templateStep = new ASPxImage();
            ASPxImage dataStep = new ASPxImage();
            ASPxImage varStep = new ASPxImage();
            ASPxImage reviewStep = new ASPxImage();

            templateOv = new Label();
            dataOv = new Label();
            varOv = new Label();
            reviewOv = new Label();
            //templateOv.CssClass = ArrowUtils.css_pageTitle();
            //dataOv.CssClass = ArrowUtils.css_pageTitle();
            //varOv.CssClass = ArrowUtils.css_pageTitle();
            //reviewOv.CssClass = ArrowUtils.css_pageTitle();

            //templateOv.Width = Unit.Pixel(600);
            //dataOv.Width = Unit.Pixel(600);
            //varOv.Width = Unit.Pixel(600);
            //reviewOv.Width = Unit.Pixel(600);


            templateOv.Text = "Choose the save location for the report definition.  " +
                              "Reports can be in the following formats: docx, rtf, xls, xlsx, pptx, and" +
                              " .xml (wordML, spreadsheetML only).";
            dataOv.Text = "Choose one or more data definition files to bind to the template.";
            varOv.Text = "Set any runtime variables; these will be passed into the template.";
            reviewOv.Text = "Review all of the details from each step before generating the report definition";

            templateStep.ImageUrl = assemblyImage;
            dataStep.ImageUrl = datasourceImage;
            varStep.ImageUrl = variableImage;
            reviewStep.ImageUrl = reviewImage;

            Table overviewTable = ArrowUtils.makeTableAlternating(ArrowUtils.createEmptyTable(9, 3, 40, 142));

            //overviewTable.Rows[1].Cells[0].VerticalAlign = VerticalAlign.Top;
            //overviewTable.Rows[3].Cells[0].VerticalAlign = VerticalAlign.Top;
            //overviewTable.Rows[5].Cells[0].VerticalAlign = VerticalAlign.Top;
            //overviewTable.Rows[7].Cells[0].VerticalAlign = VerticalAlign.Top;

            //overviewTable.Rows[1].Cells[1].VerticalAlign = VerticalAlign.Top;
            //overviewTable.Rows[3].Cells[1].VerticalAlign = VerticalAlign.Top;
            //overviewTable.Rows[5].Cells[1].VerticalAlign = VerticalAlign.Top;
            //overviewTable.Rows[7].Cells[1].VerticalAlign = VerticalAlign.Top;
            //overviewTable.Rows[7].Cells[1].HorizontalAlign = HorizontalAlign.Center;

            overviewTable.Rows[1].Cells[0].Controls.Add(templateStep);
            overviewTable.Rows[3].Cells[0].Controls.Add(dataStep);
            overviewTable.Rows[5].Cells[0].Controls.Add(varStep);
            overviewTable.Rows[7].Cells[0].Controls.Add(reviewStep);

            overviewTable.Rows[1].Cells[1].Controls.Add(s1);
            overviewTable.Rows[3].Cells[1].Controls.Add(s2);
            overviewTable.Rows[5].Cells[1].Controls.Add(s3);
            overviewTable.Rows[7].Cells[1].Controls.Add(s4);

            overviewTable.Rows[1].Cells[2].Controls.Add(templateOv);
            overviewTable.Rows[3].Cells[2].Controls.Add(dataOv);
            overviewTable.Rows[5].Cells[2].Controls.Add(varOv);
            overviewTable.Rows[7].Cells[2].Controls.Add(reviewOv);

            overviewTable.Rows[1].Cells[2].CssClass = ArrowUtils.css_tableCell();
            overviewTable.Rows[3].Cells[2].CssClass = ArrowUtils.css_tableCell();
            overviewTable.Rows[5].Cells[2].CssClass = ArrowUtils.css_tableCell();
            overviewTable.Rows[7].Cells[2].CssClass = ArrowUtils.css_tableCell();

            if (log.IsDebugEnabled)
                log.Debug("Finished creating overview step for assemble.");

            return overviewTable;
        }
        private Table createStep1_assemble()
        {
            if (log.IsDebugEnabled)
                log.Debug("Creating step 1 for assemble.");

            Label step1Header = new Label();
            step1Header.Text = "Name the report definition file and pick output locations.";
            step1Header.ApplyStyle(ArrowUtils.headerStyle());
            step1Header.Width = Unit.Pixel(820);

            four = new Label { Text = "4." };
            five = new Label { Text = "5." };

            errorMessageLabel = new ASPxLabel();
            errorMessageLabel.Text = "";
            errorMessageLabel.ClientVisible = false;
            errorMessageLabel.ApplyStyle(ArrowUtils.errorStyle());
            errorMessageLabel.ForeColor = System.Drawing.Color.Red;

            Label title = new Label { Text = "1. Title the report definition file" };
            Label descr = new Label { Text = "2. Description" };
            Label saveLoc = new Label { Text = "3. Pick the save Location for the report definition file" };
            Label reportSaveLoc = new Label { Text = "4. Pick the output location for report generated from this report definition" };
            Label reportNameLabel = new Label { Text = "5. Provide a filename for the generated report" };

            //DocLibSelection = new Label();
            //reportOutputSel = new Label();

            //DocLibSelection.ApplyStyle(ArrowUtils.normalBoldStyle());
            //reportOutputSel.ApplyStyle(ArrowUtils.normalBoldStyle());

            titleTextbox = new ASPxTextBox();
            titleTextbox.Width = ArrowUtils.DEFAULT_TXTBX_WIDTH;
            titleTextbox.Text = (string)ViewState["AssemblyName"];

            descriptionTextbox = new ASPxMemo();
            descriptionTextbox.Width = ArrowUtils.DEFAULT_TXTBX_WIDTH;
            descriptionTextbox.Height = new Unit(40, UnitType.Pixel);
            descriptionTextbox.Text = (string)ViewState["AssemblyDescription"];

            reportNameTextBox = new TextBox();
            reportNameTextBox.Text = (string)ViewState["ReportName"];

            // output folder selector
            outputFolderSelector = new SPFileSelector(SPFileSelector.Mode.Folder);
            outputFolderSelector.Visible = true;

            // report default save folder selector
            rptOutLocFolderSelector = new SPFileSelector(SPFileSelector.Mode.Folder);
            rptOutLocFolderSelector.Visible = true;

            Table t1 = ArrowUtils.makeTableAlternating(ArrowUtils.createEmptyTable(12, 1, 20, WizzyWidth));
            t1.CellPadding = 8;

            t1.Rows[0].Cells[0].Controls.Add(step1Header);
            t1.Rows[0].Cells[0].CssClass = ".ms-titlearea";
            t1.Rows[1].Cells[0].Controls.Add(errorMessageLabel);
            t1.Rows[2].Cells[0].Controls.Add(title);
            t1.Rows[3].Cells[0].Controls.Add(titleTextbox);
            t1.Rows[4].Cells[0].Controls.Add(descr);
            t1.Rows[5].Cells[0].Controls.Add(descriptionTextbox);

            t1.Rows[6].Cells[0].Controls.Add(saveLoc);
            t1.Rows[7].Cells[0].Controls.Add(outputFolderSelector);
            //t1.Rows[7].Cells[2].Controls.Add(errorMessageLabel);

            t1.Rows[8].Cells[0].Controls.Add(reportSaveLoc);
            //t1.Rows[9].Cells[0].Controls.Add(menuRptOutLoc);
            t1.Rows[9].Cells[0].Controls.Add(rptOutLocFolderSelector);

            t1.Rows[10].Cells[0].Controls.Add(reportNameLabel);
            t1.Rows[11].Cells[0].Controls.Add(reportNameTextBox);

            if (log.IsDebugEnabled)
                log.Debug("Finished creating step 1 for assemble.");

            return t1;


        }
        private Table createStep2_assemble()
        {
            if (log.IsDebugEnabled)
                log.Debug("Creating step 2 for assemble.");

            ASPxLabel step2Header = new ASPxLabel();
            step2Header.Text = "Choose a data definition file for each 'Data Nickname' found in the template";
            step2Header.ApplyStyle(ArrowUtils.headerStyle());
            step2Header.Width = Unit.Pixel(820);

            //Table t = ArrowUtils.createEmptyTable(3, 4, 41, 125);
            int maxNumDataSources = NUMBER_DATASOURCES;
            Table t = ArrowUtils.makeTableAlternatingOffset(ArrowUtils.createEmptyTable(1 + maxNumDataSources, 5, 30, 125));

            // labels for each data spec field
            ASPxLabel dataName = new ASPxLabel();
            dataName.Text = "Data Nickname";
            dataName.ApplyStyle(ArrowUtils.normalBoldStyle());
            dataName.Width = Unit.Pixel(180);
            ASPxLabel datasourceSite = new ASPxLabel();
            datasourceSite.Text = "Site";
            datasourceSite.ApplyStyle(ArrowUtils.normalBoldStyle());
            datasourceSite.Width = Unit.Pixel(100);
            ASPxLabel datasourceLib = new ASPxLabel();
            datasourceLib.Text = "Library";
            datasourceLib.ApplyStyle(ArrowUtils.normalBoldStyle());
            datasourceLib.Width = Unit.Pixel(150); ;
            ASPxLabel datasourceFolder = new ASPxLabel();
            datasourceFolder.Text = "Folder";
            datasourceFolder.ApplyStyle(ArrowUtils.normalBoldStyle());
            datasourceFolder.Width = Unit.Pixel(100);
            ASPxLabel fileLabel = new ASPxLabel();
            fileLabel.Text = "File(*.datadef)";
            fileLabel.ApplyStyle(ArrowUtils.normalBoldStyle());
            fileLabel.Width = Unit.Pixel(150);

            errorMessageLabel2 = new ASPxLabel();
            errorMessageLabel2.Text = "";
            errorMessageLabel2.ClientVisible = false;
            errorMessageLabel2.ApplyStyle(ArrowUtils.errorStyle());
            errorMessageLabel2.ForeColor = System.Drawing.Color.Red;

            // add the labels
            t.Rows[0].Cells[0].Controls.Add(dataName);
            t.Rows[0].Cells[1].Controls.Add(datasourceSite);
            t.Rows[0].Cells[2].Controls.Add(datasourceLib);
            t.Rows[0].Cells[3].Controls.Add(datasourceFolder);
            t.Rows[0].Cells[4].Controls.Add(fileLabel);

            // arrays of controls for each data spec field
            dataSourceSpecLabelArray = new Label[maxNumDataSources];
            dataSourceSpecSiteDropDownListArray = new DropDownList[maxNumDataSources];
            dataSourceSpecLibraryDropDownListArray = new DropDownList[maxNumDataSources];
            dataSourceSpecFolderDropDownListArray = new DropDownList[maxNumDataSources];
            dataSourceSpecFileDropDownListArray = new DropDownList[maxNumDataSources];

            // instantiate dropdownlistarrays
            for (int i = 0; i < maxNumDataSources; i++)
            {
                // initialize name label
                dataSourceSpecLabelArray[i] = new Label();
                dataSourceSpecLabelArray[i].Visible = false;
                t.Rows[1 + i].Cells[0].Controls.Add(dataSourceSpecLabelArray[i]);

                // initialize list of sites
                dataSourceSpecSiteDropDownListArray[i] = new DropDownList();
                dataSourceSpecSiteDropDownListArray[i].ID = "dataSourceSpecSiteDropDownList" + i.ToString();
                dataSourceSpecSiteDropDownListArray[i].AutoPostBack = true;
                dataSourceSpecSiteDropDownListArray[i].SelectedIndexChanged += new EventHandler(DataSourceSpecSiteDropDownListArraySelectedIndexChanged_assemble);
                dataSourceSpecSiteDropDownListArray[i].Visible = false;
                t.Rows[1 + i].Cells[1].Controls.Add(dataSourceSpecSiteDropDownListArray[i]);

                // initialize list of data def libraries
                dataSourceSpecLibraryDropDownListArray[i] = new DropDownList();
                dataSourceSpecLibraryDropDownListArray[i].ID = "dataSourceSpecLibraryDropDownList" + i.ToString();
                dataSourceSpecLibraryDropDownListArray[i].AutoPostBack = true;
                dataSourceSpecLibraryDropDownListArray[i].SelectedIndexChanged += new EventHandler(DataSourceSpecLibraryDropDownListArraySelectedIndexChanged_assemble);
                dataSourceSpecLibraryDropDownListArray[i].Visible = false;
                t.Rows[1 + i].Cells[2].Controls.Add(dataSourceSpecLibraryDropDownListArray[i]);

                // initialize list of folders
                dataSourceSpecFolderDropDownListArray[i] = new DropDownList();
                dataSourceSpecFolderDropDownListArray[i].ID = "dataSourceSpecFolderDropDownListArray" + i.ToString();
                dataSourceSpecFolderDropDownListArray[i].AutoPostBack = true;
                dataSourceSpecFolderDropDownListArray[i].SelectedIndexChanged += new EventHandler(DataSourceSpecFolderDropDownListArraySelectedIndexChanged_assemble);
                dataSourceSpecFolderDropDownListArray[i].Visible = false;
                t.Rows[1 + i].Cells[3].Controls.Add(dataSourceSpecFolderDropDownListArray[i]);

                // initialize list of data def files
                dataSourceSpecFileDropDownListArray[i] = new DropDownList();
                dataSourceSpecFileDropDownListArray[i].Visible = false;
                t.Rows[1 + i].Cells[4].Controls.Add(dataSourceSpecFileDropDownListArray[i]);
            }

            Table container = ArrowUtils.createEmptyTable(3, 1, 20, 150);
            container.Rows[0].Cells[0].Controls.Add(step2Header);
            container.Rows[0].Cells[0].CssClass = ".ms-titlearea";
            container.Rows[1].Cells[0].Controls.Add(errorMessageLabel2);
            container.Rows[2].Cells[0].Controls.Add(t);

            if (log.IsDebugEnabled)
                log.Debug("Finished creating step 2 for assemble.");

            return container;
        }
        private Table createStep3_assemble()
        {
            if (log.IsDebugEnabled)
                log.Debug("Creating step 3 for assemble.");

            ASPxLabel step3Header = new ASPxLabel();
            step3Header.Text = "Set the values for the  following variables.";
            step3Header.ApplyStyle(ArrowUtils.headerStyle());
            step3Header.Width = Unit.Pixel(700);

            Table t = ArrowUtils.makeTableAlternatingOffset(ArrowUtils.createEmptyTable(1 + MAX_NUMBER_VARIABLES, 4, 20, 125)); // 41 -> 0

            ASPxLabel varName = new ASPxLabel();
            varName.Text = "Variable name";
            varName.ApplyStyle(ArrowUtils.normalBoldStyle());
            varName.Width = Unit.Pixel(200);
            //ASPxLabel required = new ASPxLabel();
            //required.Text = "Required ?  ";
            //required.ApplyStyle(ArrowUtils.normalBoldStyle());
            //required.Width = Unit.Pixel(180);
            //ASPxLabel hidden = new ASPxLabel();
            //hidden.Text = "Hidden ?  ";
            //hidden.ApplyStyle(ArrowUtils.normalBoldStyle());
            //hidden.Width = Unit.Pixel(160);
            ASPxLabel type = new ASPxLabel();
            type.Text = "Type";
            type.ApplyStyle(ArrowUtils.normalBoldStyle());
            type.Width = Unit.Pixel(150);
            ASPxLabel defaultVal = new ASPxLabel();
            defaultVal.Text = "Default value";
            defaultVal.ApplyStyle(ArrowUtils.normalBoldStyle());
            defaultVal.Width = Unit.Pixel(150);
            ASPxLabel descr = new ASPxLabel();
            descr.Text = "Description";
            descr.ApplyStyle(ArrowUtils.normalBoldStyle());
            descr.Width = Unit.Pixel(150);

            //0,0
            t.Rows[0].Cells[0].Controls.Add(varName);
            //0,1
            //t.Rows[0].Cells[1].Controls.Add(required);
            //0,2
            //t.Rows[0].Cells[2].Controls.Add(hidden);
            //0,3
            t.Rows[0].Cells[1].Controls.Add(type);
            //0,4
            t.Rows[0].Cells[2].Controls.Add(defaultVal);
            //0,5
            t.Rows[0].Cells[3].Controls.Add(descr);

            variableNameLabelArray = new Label[MAX_NUMBER_VARIABLES];
            variableRequiredCheckBoxArray = new CheckBox[MAX_NUMBER_VARIABLES];
            variableHiddenCheckBoxArray = new CheckBox[MAX_NUMBER_VARIABLES];
            variableTypeLabels = new Label[MAX_NUMBER_VARIABLES];
            variableDefaultValueTextBoxArray = new TextBox[MAX_NUMBER_VARIABLES];
            variableDescriptionTextBoxArray = new TextBox[MAX_NUMBER_VARIABLES];

            variableDataNameTextBoxArray = new TextBox[MAX_NUMBER_VARIABLES];
            variableCountTextBoxArray = new TextBox[MAX_NUMBER_VARIABLES];
            variableAllTextBoxArray = new TextBox[MAX_NUMBER_VARIABLES];
            variableValueTextBoxArray = new TextBox[MAX_NUMBER_VARIABLES];
            variableDataNameLiteralControlArray = new Label[MAX_NUMBER_VARIABLES];
            variableCountLabelLiteralControlArray = new Label[MAX_NUMBER_VARIABLES];
            variableAllLabelLiteralControlArray = new Label[MAX_NUMBER_VARIABLES];
            variableValueLabelLiteralControlArray = new Label[MAX_NUMBER_VARIABLES];

            for (int i = 0; i < MAX_NUMBER_VARIABLES; i++)
            {
                variableNameLabelArray[i] = new Label();
                t.Rows[1 + i].Cells[0].Controls.Add(variableNameLabelArray[i]);

                variableRequiredCheckBoxArray[i] = new CheckBox();
                //t.Rows[1 + i].Cells[1].Controls.Add(variableRequiredCheckBoxArray[i]);

                variableHiddenCheckBoxArray[i] = new CheckBox();
                //t.Rows[1 + i].Cells[2].Controls.Add(variableHiddenCheckBoxArray[i]);

                variableTypeLabels[i] = new Label();
                t.Rows[1 + i].Cells[1].Controls.Add(variableTypeLabels[i]);

                variableDataNameLiteralControlArray[i] = new Label() { Text = "<br/>Data Source Name<br/>" };
                variableDataNameLiteralControlArray[i].Visible = false;
                //t.Rows[1 + i].Cells[3].Controls.Add(variableDataNameLiteralControlArray[i]);
                variableDataNameTextBoxArray[i] = new TextBox();
                //t.Rows[1 + i].Cells[3].Controls.Add(variableDataNameTextBoxArray[i]);
                variableCountLabelLiteralControlArray[i] = new Label() { Text = "<br/>COUNT(SELECT)<br/>" };
                //variableCountLabelLiteralControlArray[i].Visible = false;
                //t.Rows[1 + i].Cells[3].Controls.Add(variableCountLabelLiteralControlArray[i]);
                variableCountTextBoxArray[i] = new TextBox();
                //t.Rows[1 + i].Cells[3].Controls.Add(variableCountTextBoxArray[i]);
                variableAllLabelLiteralControlArray[i] = new Label() { Text = "<br/>SELECT(ALL)<br/>" };
                //variableAllLabelLiteralControlArray[i].Visible = false;
                //t.Rows[1 + i].Cells[3].Controls.Add(variableAllLabelLiteralControlArray[i]);
                variableAllTextBoxArray[i] = new TextBox();
                //t.Rows[1 + i].Cells[3].Controls.Add(variableAllTextBoxArray[i]);
                variableValueLabelLiteralControlArray[i] = new Label() { Text = "<br/>SELECT(VALUE)<br/>" };
                //variableValueLabelLiteralControlArray[i].Visible = false;
                //t.Rows[1 + i].Cells[3].Controls.Add(variableValueLabelLiteralControlArray[i]);
                variableValueTextBoxArray[i] = new TextBox();
                //t.Rows[1 + i].Cells[3].Controls.Add(variableValueTextBoxArray[i]);

                variableDefaultValueTextBoxArray[i] = new TextBox();
                t.Rows[1 + i].Cells[2].Controls.Add(variableDefaultValueTextBoxArray[i]);

                variableDescriptionTextBoxArray[i] = new TextBox();
                variableDescriptionTextBoxArray[i].TextMode = TextBoxMode.MultiLine;
                t.Rows[1 + i].Cells[3].Controls.Add(variableDescriptionTextBoxArray[i]);
            }
            Table container = ArrowUtils.createEmptyTable(2, 1, 41, 150);
            container.Rows[0].Cells[0].Controls.Add(step3Header);
            container.Rows[0].Cells[0].CssClass = ".ms-titlearea";
            container.Rows[1].Cells[0].Controls.Add(t);

            if (log.IsDebugEnabled)
                log.Debug("Finished creating step 3 for assemble.");

            return container;
        }
        private Table createStep4_assemble()
        {
            if (log.IsDebugEnabled)
                log.Debug("Creating step 4 for assemble.");

            Table toReturn = ArrowUtils.createEmptyTable(2, 1, 50, 100);
            Label step4Header = new Label();
            step4Header.Text = "Step 4: Review the information is correct.";
            step4Header.ApplyStyle(ArrowUtils.headerStyle());
            finalStatusLabel = new Label();

            Label assemblyName = new Label();
            Label description = new Label();
            Label templateFilename = new Label();
            Label saveLocation = new Label();
            Label reportOutputLocation = new Label();
            Label generatedReportName = new Label();

            assemblyName.Text = "Report definition filename:";
            description.Text = "Report definition description:";
            templateFilename.Text = "Template filename:";
            saveLocation.Text = "Report definition save location:";
            reportOutputLocation.Text = "Report output location:";
            generatedReportName.Text = "Generated report name:";

            assemblyName.ApplyStyle(ArrowUtils.normalBoldStyle());
            description.ApplyStyle(ArrowUtils.normalBoldStyle());
            templateFilename.ApplyStyle(ArrowUtils.normalBoldStyle());
            saveLocation.ApplyStyle(ArrowUtils.normalBoldStyle());
            reportOutputLocation.ApplyStyle(ArrowUtils.normalBoldStyle());
            generatedReportName.ApplyStyle(ArrowUtils.normalBoldStyle());



            assemblyName_val = new Label();
            description_val = new Label();
            templateFilename_val = new Label();
            saveLocation_val = new Label();
            reportOutputLocation_val = new Label();
            generatedReportName_val = new Label();
            assemblyName_val.Text = (string)ViewState["AssemblyName"];
            description_val.Text = (string)ViewState["AssemblyDescription"];
            templateFilename_val.Text = (string)ViewState["TemplateName"];
            saveLocation_val.Text = (string)ViewState["OutputDestination"];
            reportOutputLocation_val.Text = (string)ViewState["ReportOutputDestination"];
            generatedReportName_val.Text = (string)ViewState["ReportName"];

            assemblyName.ApplyStyle(normalBoldStyle);
            description.ApplyStyle(normalBoldStyle);
            templateFilename.ApplyStyle(normalBoldStyle);
            saveLocation.ApplyStyle(normalBoldStyle);
            reportOutputLocation.ApplyStyle(normalBoldStyle);
            generatedReportName.ApplyStyle(normalBoldStyle);

            assemblyName_val.ApplyStyle(normalStyle);
            description_val.ApplyStyle(normalStyle);
            templateFilename_val.ApplyStyle(normalStyle);
            saveLocation_val.ApplyStyle(normalStyle);
            reportOutputLocation_val.ApplyStyle(normalStyle);
            generatedReportName_val.ApplyStyle(normalStyle);

            Table t = ArrowUtils.makeTableAlternating(ArrowUtils.createEmptyTable(7, 2, 41, 125));
            t.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Right;
            t.Rows[1].Cells[0].HorizontalAlign = HorizontalAlign.Right;
            t.Rows[2].Cells[0].HorizontalAlign = HorizontalAlign.Right;
            t.Rows[3].Cells[0].HorizontalAlign = HorizontalAlign.Right;
            t.Rows[4].Cells[0].HorizontalAlign = HorizontalAlign.Right;
            t.Rows[5].Cells[0].HorizontalAlign = HorizontalAlign.Right;
            t.Rows[6].Cells[0].HorizontalAlign = HorizontalAlign.Right;

            t.Rows[0].Cells[0].VerticalAlign = VerticalAlign.Middle;
            t.Rows[1].Cells[0].VerticalAlign = VerticalAlign.Middle;
            t.Rows[2].Cells[0].VerticalAlign = VerticalAlign.Middle;
            t.Rows[3].Cells[0].VerticalAlign = VerticalAlign.Middle;
            t.Rows[4].Cells[0].VerticalAlign = VerticalAlign.Middle;
            t.Rows[5].Cells[0].VerticalAlign = VerticalAlign.Middle;
            t.Rows[6].Cells[0].VerticalAlign = VerticalAlign.Middle;

            t.Rows[0].Cells[0].Controls.Add(assemblyName);
            t.Rows[1].Cells[0].Controls.Add(description);
            t.Rows[2].Cells[0].Controls.Add(templateFilename);
            t.Rows[3].Cells[0].Controls.Add(saveLocation);
            t.Rows[4].Cells[0].Controls.Add(reportOutputLocation);
            t.Rows[5].Cells[0].Controls.Add(generatedReportName);
            t.Rows[6].Cells[1].Controls.Add(finalStatusLabel);


            t.Rows[0].Cells[1].HorizontalAlign = HorizontalAlign.Left;
            t.Rows[1].Cells[1].HorizontalAlign = HorizontalAlign.Left;
            t.Rows[2].Cells[1].HorizontalAlign = HorizontalAlign.Left;
            t.Rows[3].Cells[1].HorizontalAlign = HorizontalAlign.Left;
            t.Rows[4].Cells[1].HorizontalAlign = HorizontalAlign.Left;
            t.Rows[5].Cells[1].HorizontalAlign = HorizontalAlign.Left;
            t.Rows[6].Cells[1].HorizontalAlign = HorizontalAlign.Left;
            t.Rows[0].Cells[1].VerticalAlign = VerticalAlign.Middle;
            t.Rows[1].Cells[1].VerticalAlign = VerticalAlign.Middle;
            t.Rows[2].Cells[1].VerticalAlign = VerticalAlign.Middle;
            t.Rows[3].Cells[1].VerticalAlign = VerticalAlign.Middle;
            t.Rows[4].Cells[1].VerticalAlign = VerticalAlign.Middle;
            t.Rows[5].Cells[1].VerticalAlign = VerticalAlign.Middle;
            t.Rows[6].Cells[1].VerticalAlign = VerticalAlign.Middle;

            t.Rows[0].Cells[1].Controls.Add(assemblyName_val);
            t.Rows[1].Cells[1].Controls.Add(description_val);
            t.Rows[2].Cells[1].Controls.Add(templateFilename_val);
            t.Rows[3].Cells[1].Controls.Add(saveLocation_val);
            t.Rows[4].Cells[1].Controls.Add(reportOutputLocation_val);
            t.Rows[5].Cells[1].Controls.Add(generatedReportName_val);

            toReturn.Rows[0].Cells[0].Controls.Add(step4Header);
            toReturn.Rows[1].Cells[0].Controls.Add(t);

            if (log.IsDebugEnabled)
                log.Debug("Finished creating step 4 for assemble.");

            return toReturn;
        }
        private Table createTable_assemble(int tableNum)
        {
            if (log.IsDebugEnabled)
                log.Debug("Create table assemble begin.");

            Table t;
            switch (tableNum)
            {
                case 0:
                    t = createOverview_assemble();
                    break;
                case 1:
                    t = createStep1_assemble();
                    break;
                case 2:
                    t = createStep2_assemble();
                    break;
                case 3:
                    t = createStep3_assemble();
                    break;
                case 4:
                    t = createStep4_assemble();
                    break;
                default:
                    // Never gets here
                    t = ArrowUtils.createEmptyTable(1, 1, 1, 1);
                    break;
            }

            t.ID = "table" + tableNum;
            t.CellPadding = 8;
            //t.BorderStyle = BorderStyle.Solid;
            //t.BorderColor = Color.FromName("Black");
            //t.BorderWidth = 1;

            if (log.IsDebugEnabled)
                log.Debug("Create table assemble end.");

            return t;
        }

        private string getDataSourcePath_assemble(int num)
        {
            //SPSite siteCol = new SPSite(siteUrl);
            //SPWeb site = siteCol.OpenWeb();
            // bugbug: figure out how to get this right, siteUrl is from view state, which is different
            // than the selected site drop down
            Guid selSiteID = new Guid(dataSourceSpecSiteDropDownListArray[num].SelectedValue);
            SPWeb site = ArrowUtils.GetSPWebCollectionFromCurrentSite()[selSiteID];

            Guid dataSourceLibID = new Guid(dataSourceSpecLibraryDropDownListArray[num].SelectedValue);
            Guid dataSourceID = new Guid(dataSourceSpecFileDropDownListArray[num].SelectedValue);
            SPDocumentLibrary dataSourceLib = (SPDocumentLibrary)site.Lists[dataSourceLibID];
            string sFolderID = dataSourceSpecFolderDropDownListArray[num].SelectedValue;
            SPFolder selFolder = dataSourceLib.RootFolder;
            if (!string.IsNullOrEmpty(sFolderID))
                selFolder = site.GetFolder(new Guid(sFolderID));
            SPFile dataSourceFile = dataSourceLib.Items[dataSourceID].File;
            string dataSourceRelativePath = dataSourceFile.ServerRelativeUrl;
            string dataSourceAbsolutePath = SPContext.Current.Site.MakeFullUrl(dataSourceRelativePath);

            site.Dispose();
            //siteCol.Dispose();

            return dataSourceAbsolutePath;
        }

        bool step1Validation_assemble(out string errorMessage)
        {
            errorMessage = "Error:";
            bool result = true;
            if (titleTextbox.Text == null || titleTextbox.Text.Length <= 0)
            {
                result = false;
                errorMessage += " *Title value is not set";
            }
            if ((string)ViewState["OutputDocLibGUID"] == null)
            {
                result = false;
                errorMessage += ", No save location has been selected.";
            }
            return result;
        }
        bool step1Validation(out string errorMessage, SPFileSelectorFolderInfo outFolderInfo)
        {
            errorMessage = "Error:";
            bool result = true;
            if (titleTextbox.Text == null || titleTextbox.Text.Length <= 0)
            {
                result = false;
                errorMessage += " *Title value is not set. \n";
            }
            // output destination validation
            if (!outFolderInfo.IsSPFolder && !string.IsNullOrEmpty(outFolderInfo.Url))
            {
                result = false;
                errorMessage += " *Invalid save location for step 3. The selected directory is a website.";
            }
            else if ((string)ViewState["OutputDocLibGUID"] == null)
            {
                result = false;
                errorMessage += " *No save location has been selected \n";
            }
            // report default save location validation
            SPFileSelectorFolderInfo rptOutLocFolderInfo = rptOutLocFolderSelector.SelectedFolder;
            if (!rptOutLocFolderInfo.IsSPFolder && !string.IsNullOrEmpty(rptOutLocFolderInfo.Url))
            {
                result = false;
                errorMessage += " *Invalid save location for step 4. The selected directory is a website. \n";
            }
            else if (!string.IsNullOrEmpty(rptOutLocFolderInfo.Url) && string.IsNullOrEmpty(reportNameTextBox.Text.Trim()))
                if (dataSourceSpecFileDropDownListArray[0].SelectedValue == null || dataSourceSpecFileDropDownListArray[0].SelectedValue.Length <= 0)
                {
                    errorMessage += "*No datasource selected";
                    result = false;
                    errorMessage += " *Must set report name for step 5. \n";
                }
                else
                {
                    ViewState["ReportOutputDestination"] = ArrowUtils.BuildFolderPathDisplayString(rptOutLocFolderInfo);
                }
            return result;
        }
        bool step2Validation_assemble(out string errorMessage)
        {
            errorMessage = "Error:";
            bool result = true;
            if (dataSourceSpecFileDropDownListArray.Length > 0 && string.IsNullOrEmpty(dataSourceSpecFileDropDownListArray[0].SelectedValue))
            {
                errorMessage += "*No datasource selected";
                result = false;
            }
            return result;
        }
        void wizzy_NextButtonClick_assemble(object o, WizardNavigationEventArgs e)
        {
            if (log.IsDebugEnabled)
                log.Debug("handling next button click");

            /*
             * Should modify the code so it only updates the variables tab when coming from the
             * document selection tab. For now i will update on each tab change, that goes to the variable tab.
             */
            string errorMessage;
            switch (e.CurrentStepIndex)
            {
                case 0:
                    if (log.IsDebugEnabled)
                        log.Debug("moving from overview step");
                    break;
                case 1:
                    if (log.IsDebugEnabled)
                        log.Debug("moving from template selection step");

                    // get selected output folder info
                    SPFileSelectorFolderInfo outFolderInfo = outputFolderSelector.SelectedFolder;
                    if (!"URL".Equals(ViewState["OutputDestination"]))
                    {
                        ViewState["OutputSiteGUID"] = outFolderInfo.WebGuid;
                        ViewState["OutputDocLibGUID"] = outFolderInfo.LibGuid;
                        ViewState[VS_FOLDR_OUT_GUID] = outFolderInfo.Guid;
                        ViewState["OutputDestination"] = saveLocation_val.Text = ArrowUtils.BuildFolderPathDisplayString(outFolderInfo);
                    }

                    errorMessageLabel.ClientVisible = false;
                    if (!step1Validation(out errorMessage, outFolderInfo))
                    {
                        errorMessageLabel.Text = errorMessage;
                        errorMessageLabel.ClientVisible = true;
                        e.Cancel = true;
                        return;
                    }
                    ViewState["ReportName"] = reportNameTextBox.Text.Trim();
                    ViewState["AssemblyName"] = assemblyName_val.Text = titleTextbox.Text.Trim();
                    ViewState["AssemblyDescription"] = description_val.Text = descriptionTextbox.Text.Trim();

                    Stream templateStream = ArrowUtils.GetSPFileStream(new Guid((string)ViewState["TemplateSiteGUID"]), new Guid((string)ViewState["TemplateGUID"]));
                    TemplateMetrics tm = Report.GetMetrics(templateStream);
                    string[] neededDatasources = tm.Datasources;

                    // set their visibility to false
                    for (int i = 0; i < dataSourceSpecLabelArray.Length; i++)
                    {
                        dataSourceSpecLabelArray[i].Visible = false;
                        dataSourceSpecSiteDropDownListArray[i].Visible = false;
                        dataSourceSpecLibraryDropDownListArray[i].Visible = false;
                        dataSourceSpecFolderDropDownListArray[i].Visible = false;
                        dataSourceSpecFileDropDownListArray[i].Visible = false;
                    }

                    string singleDatasource;
                    for (int i = 0; i < neededDatasources.Length; i++)
                    {
                        dataSourceSpecSiteDropDownListArray[i].Items.Clear();
                        dataSourceSpecLibraryDropDownListArray[i].Items.Clear();
                        dataSourceSpecFolderDropDownListArray[i].Items.Clear();
                        dataSourceSpecFileDropDownListArray[i].Items.Clear();

                        dataSourceSpecSiteDropDownListArray[i].Visible = true;
                        dataSourceSpecLibraryDropDownListArray[i].Visible = true;
                        dataSourceSpecFolderDropDownListArray[i].Visible = true;
                        dataSourceSpecFileDropDownListArray[i].Visible = true;
                        dataSourceSpecLabelArray[i].Visible = true;

                        singleDatasource = neededDatasources[i];
                        if (singleDatasource == "")
                            dataSourceSpecLabelArray[i].Text = "(no name)<br/>";
                        else
                            dataSourceSpecLabelArray[i].Text = singleDatasource;

                        // get the current site
                        SPWeb curSite = SPContext.Current.Web; // currently can only read datadef files from same site as webpart

                        // populate the sites
                        SPWebCollection theWebs = ArrowUtils.GetSPWebCollectionFromCurrentSite();
                        foreach (SPWeb web in theWebs)
                        {
                            ListItem webItem = new ListItem(web.Title, web.ID.ToString());
                            if (web.ID == curSite.ID)
                                webItem.Selected = true;
                            dataSourceSpecSiteDropDownListArray[i].Items.Add(webItem);
                        }

                        // populate library lists
                        SPDocumentLibrary library = null;
                        bool isFirstLib = true;
                        foreach (SPList list in curSite.Lists)
                        {
                            if (list is SPDocumentLibrary && !list.Hidden)
                            {
                                if (isFirstLib)
                                {
                                    library = (SPDocumentLibrary)list;
                                    isFirstLib = false;
                                }
                                dataSourceSpecLibraryDropDownListArray[i].Items.Add(new ListItem(list.Title, list.ID.ToString()));
                            }
                        }

                        // populate folder lists
                        dataSourceSpecFolderDropDownListArray[i].Items.Add(new ListItem("<None>", ""));
                        if (library != null)
                        {
                            foreach (SPListItem folderItem in library.Folders)
                            {
                                SPFolder folder = folderItem.Folder;
                                if (folder != null)
                                {
                                    dataSourceSpecFolderDropDownListArray[i].Items.Add(new ListItem(folder.Name, folder.UniqueId.ToString()));
                                }
                            }
                        }


                        // populate the file list
                        if (library != null)
                        {
                            SPFolder selFolder = library.RootFolder;

                            // sort the list items
                            ArrayList sortedItems = new ArrayList();
                            foreach (SPFile item in selFolder.Files)
                            {
                                sortedItems.Add(item);
                            }
                            sortedItems.Sort(new ArrowUtils.SPFileComparer());

                            // add the file items
                            foreach (SPFile file in sortedItems)
                            {
                                if (file.Name.EndsWith(".datadef") || file.Name.EndsWith(".wrd"))
                                {
                                    string dataDefName = string.Empty;
                                    if (file.Name.EndsWith(".datadef"))
                                        dataDefName = file.Name.Trim().Substring(0, file.Name.Trim().LastIndexOf(".datadef"));
                                    else
                                        dataDefName = file.Name.Trim().Substring(0, file.Name.Trim().LastIndexOf(".wrd"));
                                    dataSourceSpecFileDropDownListArray[i].Items.Add(new ListItem(dataDefName, file.Item.UniqueId.ToString()));
                                }
                            }
                        }
                    }
                    if (neededDatasources.Length < 1)
                    {
                        bool hasVars = tm.Vars.Length > 0;

                        if (hasVars)
                        {
                            setupVarTable(tm);
                            wizzy.ActiveStepIndex = 3;
                        }
                        else
                        {
                            // no vars
                            wizzy.ActiveStepIndex = 4;
                        }
                    }
                    break;
                case 2:
                    if (log.IsDebugEnabled)
                        log.Debug("moving from datasource selection step");
                    errorMessageLabel2.ClientVisible = false;

                    if (!step2Validation_assemble(out errorMessage))
                    {
                        errorMessageLabel2.Text = "Error: No data definition is selected";
                        errorMessageLabel2.ClientVisible = true;
                        e.Cancel = true;
                        return;
                    }
                    Stream templateStream2 = ArrowUtils.GetSPFileStream(new Guid((string)ViewState["TemplateSiteGUID"]), new Guid((string)ViewState["TemplateGUID"]));
                    TemplateMetrics tm2 = Report.GetMetrics(templateStream2);

                    if (ArrowUtils.GetNeededVarNamesForDisplay(tm2, log).Length <= 0)
                    {
                        wizzy.ActiveStepIndex = 4;
                        return;
                    }

                    setupVarTable(tm2);
                    break;
                case 3:
                    if (log.IsDebugEnabled)
                        log.Debug("moving from parameter definition step");
                    break;
                case 4:
                    if (log.IsDebugEnabled)
                        log.Debug("moving from review step");
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// Determines if vars are needed, and if so, sets up the var table so that vars can be entered.
        /// </summary>
        /// <param name="tm2"></param>
        private void setupVarTable(TemplateMetrics tm2)
        {
            TemplateMetrics tm = ArrowUtils.GetTemplateMetrics(new Guid((string)ViewState[VS_TEMPL_SITE_GUID]), new Guid((string)ViewState[VS_TEMPL_GUID]));
            IList<TemplateVariable> displayVars = ArrowUtils.GetTemplateVarsForDisplay(tm, log);
            bool variablesDefined = displayVars.Count > 0;

            //DataSourceProfileCollection dspc = dg.AllDataSources;

            // need to populate variables
            for (int i = displayVars.Count; i < variableNameLabelArray.Length; i++)
            {
                //bugbug - setting values on object[i], but then setting object[i] = null
                // setting object null should be enough then
                #region hide
                variableNameLabelArray[i].Visible = false;
                variableRequiredCheckBoxArray[i].Visible = false;
                variableHiddenCheckBoxArray[i].Visible = false;
                variableTypeLabels[i].Visible = false;
                variableDefaultValueTextBoxArray[i].Visible = false;
                variableDescriptionTextBoxArray[i].Visible = false;
                variableCountTextBoxArray[i].Visible = false;
                variableAllTextBoxArray[i].Visible = false;
                variableValueTextBoxArray[i].Visible = false;
                variableCountLabelLiteralControlArray[i].Visible = false;
                variableAllLabelLiteralControlArray[i].Visible = false;
                variableValueLabelLiteralControlArray[i].Visible = false;
                variableDataNameTextBoxArray[i].Visible = false;
                variableDataNameLiteralControlArray[i].Visible = false;
                #endregion hide
                variableNameLabelArray[i].Text = "";
                #region nullify
                variableNameLabelArray[i] = null;
                variableRequiredCheckBoxArray[i] = null;
                variableHiddenCheckBoxArray[i] = null;
                variableTypeLabels[i] = null;
                variableDefaultValueTextBoxArray[i] = null;
                variableDescriptionTextBoxArray[i] = null;
                variableCountTextBoxArray[i] = null;
                variableAllTextBoxArray[i] = null;
                variableValueTextBoxArray[i] = null;
                variableCountLabelLiteralControlArray[i] = null;
                variableAllLabelLiteralControlArray[i] = null;
                variableValueLabelLiteralControlArray[i] = null;
                variableDataNameTextBoxArray[i] = null;
                variableDataNameLiteralControlArray[i] = null;
                #endregion nullify
            }

            for (int i = 0; i < displayVars.Count; i++)
            {
                //variableTypeLabels[i].Items.Clear();

                #region hide
                variableNameLabelArray[i].Visible = true;
                variableRequiredCheckBoxArray[i].Visible = true;
                variableHiddenCheckBoxArray[i].Visible = true;
                variableTypeLabels[i].Visible = true;
                variableDefaultValueTextBoxArray[i].Visible = true;
                variableDescriptionTextBoxArray[i].Visible = true;

                variableCountTextBoxArray[i].Visible = true;
                variableAllTextBoxArray[i].Visible = true;
                variableValueTextBoxArray[i].Visible = true;
                variableCountLabelLiteralControlArray[i].Visible = true;
                variableAllLabelLiteralControlArray[i].Visible = true;
                variableValueLabelLiteralControlArray[i].Visible = true;
                variableDataNameTextBoxArray[i].Visible = true;
                variableDataNameLiteralControlArray[i].Visible = true;
                #endregion hide

                variableNameLabelArray[i].Text = displayVars[i].Name;

                if (variablesDefined)
                {
                    try
                    {
                        variableRequiredCheckBoxArray[i].Checked = displayVars[i].Required;
                        switch (displayVars[i].VarType)
                        {
                            case TemplateVariable.VAR_TYPE.CURRENCY:
                                variableTypeLabels[i].Text = "Currency";
                                break;
                            case TemplateVariable.VAR_TYPE.DATE:
                                variableTypeLabels[i].Text = "Date";
                                break;
                            case TemplateVariable.VAR_TYPE.INTEGER:
                                variableTypeLabels[i].Text = "Integer";
                                break;
                            case TemplateVariable.VAR_TYPE.FLOAT:
                                variableTypeLabels[i].Text = "Float";
                                break;
                            case TemplateVariable.VAR_TYPE.SELECT:
                                variableTypeLabels[i].Text = "Select";

                                variableCountTextBoxArray[i].Text = displayVars[i].Dataset.SelectCount;
                                variableAllTextBoxArray[i].Text = displayVars[i].Dataset.Select;
                                variableValueTextBoxArray[i].Text = displayVars[i].Dataset.SelectCheck;
                                variableDataNameTextBoxArray[i].Text = displayVars[i].Datasource;
                                break;
                            case TemplateVariable.VAR_TYPE.TEXT:
                                variableTypeLabels[i].Text = "Text";
                                break;
                        }
                        if (displayVars[i].DefaultValues.Length == 0)
                        {
                            variableDefaultValueTextBoxArray[i].Text = "";//bugbug
                        }
                        else
                        {
                            variableDefaultValueTextBoxArray[i].Text = (string)displayVars[i].DefaultValues[0].Value;
                        }

                        variableDescriptionTextBoxArray[i].Text = displayVars[i].Description;
                    }
                    catch
                    {
                    }
                }
            }
        }

        /// <summary>
        /// Handles the finish button click event for generating a report definition.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void wizzy_FinishButtonClick_assemble(object sender, WizardNavigationEventArgs e)
        {
            if (log.IsDebugEnabled)
                log.Debug("handling finish button click");

            // reset status
            finalStatusLabel.Text = string.Empty;

            // validate asm name
            string asmName = (string)ViewState["AssemblyName"];
            if (string.IsNullOrEmpty(asmName) || string.IsNullOrEmpty(asmName.Trim()))
            {
                finalStatusLabel.ForeColor = Color.FromName("Red");
                finalStatusLabel.Text = "Error: Title is required and can not be blank.";
                return;
            }
            asmName = asmName.Trim();

            // get template file path
            SPDocumentLibrary templateLib = ArrowUtils.getDocLibObject(
                (string)ViewState["TemplateSiteGUID"], (string)ViewState["TemplateDocLibGUID"]);
            SPFile templateSPFile = ArrowUtils.GetSPFileFromDocLib(templateLib, (string)ViewState["TemplateGUID"]);
            string templateAbsolutePath = getAbsPathFromSPFile(templateSPFile);

            // ensure valid asm description
            string asmDesc = (string)ViewState["AssemblyDescription"];
            asmDesc = asmDesc == null ? string.Empty : asmDesc.Trim();

            //bugbug: don't delete!
            // the following code generates a large string, and is a good candidate for unit testing.
            // we can't put it directly into a method, because it uses globals (not testable).
            // and we can't pass the globals into the method because there's to many (14).
            // what we should do is generate a ReportAssemblyInfo object, and it should have
            // this method that writes it to a string, or perhaps all the way to the file.
            //asm name
            //asm desc
            //template path
            //dataSourceSpecFileDropDownListArray
            //dataSourceSpecLabelArray
            //variableNameLabelArray
            //variableDescriptionTextBoxArray
            //variableRequiredCheckBoxArray
            //variableTypeLabels
            //variableDefaultValueTextBoxArray
            //variableDataNameTextBoxArray
            //variableCountTextBoxArray
            //variableAllTextBoxArray
            //variableValueTextBoxArray

            // begin creating file
            XmlDocument xDoc = new XmlDocument();
            XmlElement ndRptDef = xDoc.CreateElement("reportdef");
            xDoc.AppendChild(ndRptDef);
            XmlElement ndTitle = xDoc.CreateElement("title");
            ndRptDef.AppendChild(ndTitle);
            ndTitle.InnerText = asmName;
            XmlElement ndDesc = xDoc.CreateElement("description");
            ndRptDef.AppendChild(ndDesc);
            ndDesc.InnerText = asmDesc;
            XmlElement ndTempl = xDoc.CreateElement("template");
            ndRptDef.AppendChild(ndTempl);
            ndTempl.InnerText = templateAbsolutePath;

            for (int i = 0; i < dataSourceSpecLibraryDropDownListArray.Length; i++)
            {
                if (dataSourceSpecLabelArray[i].Text.Equals(string.Empty))
                    break;
                String dsName = dataSourceSpecLabelArray[i].Text;
                if (dsName == "(no name)<br/>")
                    dsName = "";
                String dsPath = getDataSourcePath_assemble(i);

                XmlElement ndDataSource = xDoc.CreateElement("dataSource");
                ndRptDef.AppendChild(ndDataSource);
                XmlElement ndDataSourceName = xDoc.CreateElement("dataSourceName");
                ndDataSource.AppendChild(ndDataSourceName);
                ndDataSourceName.InnerText = dsName;
                XmlElement ndDataSourcePath = xDoc.CreateElement("dataSourcePath");
                ndDataSource.AppendChild(ndDataSourcePath);
                ndDataSourcePath.InnerText = dsPath;
            }
            
            SPFileSelectorFolderInfo defaultReportFolder = rptOutLocFolderSelector.SelectedFolder;
            bool containsDefaultSaveLocation = !string.IsNullOrEmpty(defaultReportFolder.Url) && defaultReportFolder.IsSPFolder;
            bool containsDefaultReportName = !string.IsNullOrEmpty((string)ViewState["ReportName"]);
            if (containsDefaultSaveLocation || containsDefaultReportName)
            {
                XmlElement ndRunDefaults = xDoc.CreateElement("runDefaults");
                ndRptDef.AppendChild(ndRunDefaults);
                if (containsDefaultSaveLocation)
                {
                    XmlElement ndSaveSites = xDoc.CreateElement("saveSite");
                    ndRunDefaults.AppendChild(ndSaveSites);
                    ndSaveSites.InnerText = ArrowUtils.getRootSPSite().ID.ToString();
                    XmlElement ndSaveWeb = xDoc.CreateElement("saveWeb");
                    ndRunDefaults.AppendChild(ndSaveWeb);
                    ndSaveWeb.InnerText = defaultReportFolder.WebGuid;
                    XmlElement ndSaveLib = xDoc.CreateElement("saveLib");
                    ndRunDefaults.AppendChild(ndSaveLib);
                    ndSaveLib.InnerText = defaultReportFolder.LibGuid;
                    XmlElement ndSaveFolder = xDoc.CreateElement("saveFolder");
                    ndRunDefaults.AppendChild(ndSaveFolder);
                    ndSaveFolder.InnerText = defaultReportFolder.Guid;
                }
                if (containsDefaultReportName)
                {
                    XmlElement ndReportName = xDoc.CreateElement("reportName");
                    ndRunDefaults.AppendChild(ndReportName);
                    ndReportName.InnerText = (string)ViewState["ReportName"];
                }
            }
            
            for (int i = 0; i < variableNameLabelArray.Length; i++)
            {
                if (variableNameLabelArray[i].Text.Equals(string.Empty))
                    break;

                XmlElement ndVariable = xDoc.CreateElement("variable");
                ndRptDef.AppendChild(ndVariable);
                XmlElement ndVariableName = xDoc.CreateElement("variableName");
                ndVariable.AppendChild(ndVariableName);
                ndVariableName.InnerText = variableNameLabelArray[i].Text;
                XmlElement ndVariableDesc = xDoc.CreateElement("variableDescription");
                ndVariable.AppendChild(ndVariableDesc);
                ndVariableDesc.InnerText = variableDescriptionTextBoxArray[i].Text.Trim();
                XmlElement ndVariableReq = xDoc.CreateElement("variableRequired");
                ndVariable.AppendChild(ndVariableReq);
                ndVariableReq.InnerText = variableRequiredCheckBoxArray[i].Checked.ToString();
                XmlElement ndVariableHidden = xDoc.CreateElement("variableHidden");
                ndVariable.AppendChild(ndVariableHidden);
                ndVariableHidden.InnerText = variableHiddenCheckBoxArray[i].Checked.ToString();
                XmlElement ndVariableType = xDoc.CreateElement("variableType");
                ndVariable.AppendChild(ndVariableType);
                ndVariableType.InnerText = variableTypeLabels[i].Text;
                XmlElement ndVariableDefault = xDoc.CreateElement("variableDefault");
                ndVariable.AppendChild(ndVariableDefault);
                ndVariableDefault.InnerText = variableDefaultValueTextBoxArray[i].Text.Trim();
                XmlElement ndVariableDataName = xDoc.CreateElement("variableDataName");
                ndVariable.AppendChild(ndVariableDataName);
                ndVariableDataName.InnerText = variableDataNameTextBoxArray[i].Text.Trim();
                XmlElement ndVariableSelectCount = xDoc.CreateElement("variableSelectCount");
                ndVariable.AppendChild(ndVariableSelectCount);
                ndVariableSelectCount.InnerText = variableCountTextBoxArray[i].Text.Trim();
                XmlElement ndVariableSelectAll = xDoc.CreateElement("variableSelectAll");
                ndVariable.AppendChild(ndVariableSelectAll);
                ndVariableSelectAll.InnerText = variableAllTextBoxArray[i].Text.Trim();
                XmlElement ndVariableSelectValue = xDoc.CreateElement("variableSelectValue");
                ndVariable.AppendChild(ndVariableSelectValue);
                ndVariableSelectValue.InnerText = variableValueTextBoxArray[i].Text.Trim();
            }

            string sFileContents = string.Format("<?xml version=\"1.0\" encoding=\"UTF-8\"?>{0}", xDoc.OuterXml);
            string asmFilename = string.Format("{0}.reportdef", asmName);
            SPDocumentLibrary docLib = ArrowUtils.getDocLibObject((string)ViewState["OutputSiteGUID"], (string)ViewState["OutputDocLibGUID"]);
            SPWeb site = docLib.ParentWeb;
            string outFolderGuid = (string)ViewState[VS_FOLDR_OUT_GUID];
            ArrowUtils.CreateAndAddFileFromString(sFileContents, asmFilename, (string)ViewState["OutputDocLibGUID"], site, outFolderGuid);

            finalStatusLabel.ForeColor = Color.FromName("Blue");
            finalStatusLabel.Text = "Report definition file successfully created.";
        }
        void DataSourceSpecLibraryDropDownListArraySelectedIndexChanged_assemble(object o, EventArgs e)
        {
            if (log.IsDebugEnabled)
                log.Debug("handling datadef lib changed");

            // get index of dropdown list in list array; this has to be done to match it
            // up with the correct file list to update.
            int index = -1;
            for (int i = 0; i < dataSourceSpecLibraryDropDownListArray.Length; i++)
            {
                if (o.Equals(dataSourceSpecLibraryDropDownListArray[i]))
                {
                    index = i;
                    break;
                }
            }
            if (index == -1) //bugbug: throw exception?
                return;

            // get the new library
            Guid selSiteID = new Guid(dataSourceSpecSiteDropDownListArray[index].SelectedValue);
            SPWeb site = ArrowUtils.GetSPWebCollectionFromCurrentSite()[selSiteID];
            Guid libraryID = new Guid(dataSourceSpecLibraryDropDownListArray[index].SelectedValue);
            SPDocumentLibrary library = (SPDocumentLibrary)site.Lists[libraryID];

            // populate the folder list
            dataSourceSpecFolderDropDownListArray[index].Items.Clear();
            dataSourceSpecFolderDropDownListArray[index].Items.Add(new ListItem("<None>", ""));
            if (library != null)
            {
                foreach (SPListItem folderItem in library.Folders)
                {
                    SPFolder folder = folderItem.Folder;
                    if (folder != null)
                    {
                        dataSourceSpecFolderDropDownListArray[index].Items.Add(new ListItem(folder.Name, folder.UniqueId.ToString()));
                    }
                }
            }


            // populate the file list
            dataSourceSpecFileDropDownListArray[index].Items.Clear();
            if (library != null)
            {
                SPFolder selFolder = library.RootFolder;

                // sort the list items
                ArrayList sortedItems = new ArrayList();
                foreach (SPFile item in selFolder.Files)
                {
                    sortedItems.Add(item);

                }
                sortedItems.Sort(new ArrowUtils.SPFileComparer());

                // add the file items
                foreach (SPFile file in sortedItems)
                {
                    if (file.Name.EndsWith(".datadef") || file.Name.EndsWith(".wrd"))
                    {
                        string dataDefName = string.Empty;
                        if (file.Name.EndsWith(".datadef"))
                            dataDefName = file.Name.Trim().Substring(0, file.Name.Trim().LastIndexOf(".datadef"));
                        else
                            dataDefName = file.Name.Trim().Substring(0, file.Name.Trim().LastIndexOf(".wrd"));
                        dataSourceSpecFileDropDownListArray[index].Items.Add(new ListItem(dataDefName, file.Item.UniqueId.ToString()));
                    }
                }
            }
        }
        void DataSourceSpecFolderDropDownListArraySelectedIndexChanged_assemble(object sender, EventArgs e)
        {
            if (log.IsDebugEnabled)
                log.Debug("handle datadef folder changed");

            // get index of dropdown list in list array; this has to be done to match it
            // up with the correct file list to update.
            int index = -1;
            for (int i = 0; i < dataSourceSpecFolderDropDownListArray.Length; i++)
            {
                if (sender.Equals(dataSourceSpecFolderDropDownListArray[i]))
                {
                    index = i;
                    break;
                }
            }
            if (index == -1) //bugbug: throw exception?
                return;

            // get the new library
            Guid selSiteID = new Guid(dataSourceSpecSiteDropDownListArray[index].SelectedValue);
            SPWeb site = ArrowUtils.GetSPWebCollectionFromCurrentSite()[selSiteID];
            Guid libraryID = new Guid(dataSourceSpecLibraryDropDownListArray[index].SelectedValue);
            SPDocumentLibrary library = (SPDocumentLibrary)site.Lists[libraryID];
            string sFolderID = dataSourceSpecFolderDropDownListArray[index].SelectedValue;
            SPFolder selFolder = null;
            if (string.IsNullOrEmpty(sFolderID))
                selFolder = library.RootFolder;
            else
            {
                Guid folderID = new Guid(sFolderID);
                selFolder = site.GetFolder(folderID);
            }

            // populate the file list
            dataSourceSpecFileDropDownListArray[index].Items.Clear();
            if (library != null)
            {
                // sort the list items
                ArrayList sortedItems = new ArrayList();
                foreach (SPFile item in selFolder.Files)
                {
                    sortedItems.Add(item);
                }
                sortedItems.Sort(new ArrowUtils.SPFileComparer());

                // add the file items
                foreach (SPFile file in sortedItems)
                {
                    if (file.Name.EndsWith(".datadef") || file.Name.EndsWith(".wrd"))
                    {
                        string dataDefName = string.Empty;
                        if (file.Name.EndsWith(".datadef"))
                            dataDefName = file.Name.Trim().Substring(0, file.Name.Trim().LastIndexOf(".datadef"));
                        else
                            dataDefName = file.Name.Trim().Substring(0, file.Name.Trim().LastIndexOf(".wrd"));
                        dataSourceSpecFileDropDownListArray[index].Items.Add(new ListItem(dataDefName, file.Item.UniqueId.ToString()));
                    }
                }
            }
        }
        void DataSourceSpecSiteDropDownListArraySelectedIndexChanged_assemble(object sender, EventArgs e)
        {
            if (log.IsDebugEnabled)
                log.Debug("handle datadef site changed");

            // get index of dropdown list in list array; this has to be done to match it
            // up with the correct file list to update.
            int index = -1;
            for (int i = 0; i < dataSourceSpecSiteDropDownListArray.Length; i++)
            {
                if (sender.Equals(dataSourceSpecSiteDropDownListArray[i]))
                {
                    index = i;
                    break;
                }
            }
            if (index == -1) //bugbug: throw exception?
                return;

            // get the selected site
            Guid selSiteID = new Guid(dataSourceSpecSiteDropDownListArray[index].SelectedValue);
            SPWeb selSite = ArrowUtils.GetSPWebCollectionFromCurrentSite()[selSiteID];

            // populate library list
            SPDocumentLibrary library = null;
            bool isFirstLib = true;
            dataSourceSpecLibraryDropDownListArray[index].Items.Clear();
            foreach (SPList list in selSite.Lists)
            {
                if (list is SPDocumentLibrary && !list.Hidden)
                {
                    if (isFirstLib)
                    {
                        library = (SPDocumentLibrary)list;
                        isFirstLib = false;
                    }
                    dataSourceSpecLibraryDropDownListArray[index].Items.Add(new ListItem(list.Title, list.ID.ToString()));
                }
            }

            // populate the folder list
            dataSourceSpecFolderDropDownListArray[index].Items.Clear();
            dataSourceSpecFolderDropDownListArray[index].Items.Add(new ListItem("<None>", ""));
            if (library != null)
            {
                foreach (SPListItem folderItem in library.Folders)
                {
                    SPFolder folder = folderItem.Folder;
                    if (folder != null)
                    {
                        dataSourceSpecFolderDropDownListArray[index].Items.Add(new ListItem(folder.Name, folder.UniqueId.ToString()));
                    }
                }
            }

            // populate the file list
            dataSourceSpecFileDropDownListArray[index].Items.Clear();
            if (library != null)
            {
                SPFolder selFolder = library.RootFolder;

                // sort the list items
                ArrayList sortedItems = new ArrayList();
                foreach (SPFile item in selFolder.Files)
                {
                    sortedItems.Add(item);
                }
                sortedItems.Sort(new ArrowUtils.SPFileComparer());

                // add the file items
                foreach (SPFile file in sortedItems)
                {
                    if (file.Name.EndsWith(".datadef") || file.Name.EndsWith(".wrd"))
                    {
                        string dataDefName = string.Empty;
                        if (file.Name.EndsWith(".datadef"))
                            dataDefName = file.Name.Trim().Substring(0, file.Name.Trim().LastIndexOf(".datadef"));
                        else
                            dataDefName = file.Name.Trim().Substring(0, file.Name.Trim().LastIndexOf(".wrd"));
                        dataSourceSpecFileDropDownListArray[index].Items.Add(new ListItem(dataDefName, file.Item.UniqueId.ToString()));
                    }
                }
            }
        }

        #endregion
    }
}
